% Notation
%q[ ] # Non-interpolated String (except for \\ \[ and \]) %Q[ ] # Interpolated String (default) %r[ ] # Interpolated Regexp (flags can appear after the closing delimiter) %i[ ] # Non-interpolated Array of symbols, separated by whitespace %I[ ] # Interpolated Array of symbols, separated by whitespace %w[ ] # Non-interpolated Array of words, separated by whitespace %W[ ] # Interpolated Array of words, separated by whitespace %x[ ] # Interpolated shell command
nested = Hash.new { |hash, key| hash[key] = Hash.new(&hash.default_proc) } nested[:x][:y][:z] = "value" nested #=> {:x=>{:y=>{:z=>"value"}} zoo = Hash.new { |hash, key| hash[key] = 'some default value for `#{key}`' } zoo[:foo] #=> "some default value for `foo`" foo = Hash.new 'some default value' foo[:zoo] #=> "some default value
Tap
class Foo attr_accessor :var end Foo.new.tap do |foo| foo.var = 'some data' end
Lazy
range = 1..Float::INFINITY #=> 1..Infinity range.map { |x| x+x }.first(10) #=> infinite loop range.lazy.map { |x| x+x }.first(10) #=> [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Wrap method
(1..5).each &method(:puts) method(:puts)["args"] #=> "args"
Struct
Struct.new('Tuple', :first, :second) do def pair "(#{first}, #{second})" end end struct = Struct::Tuple.new('left', 'right') struct.pair #=> "(left, right)"
Merge trick
a = {a: 1, b: 2, c: 3} b = {a: 3, b: 2, c: 1} a.merge(b) {|key, first, second| first + second } #=> {a: 4, b: 4, c: 4}Get method location
self.method(:highlight).source_location
No comments:
Post a Comment