Last Updated: April 11, 2016
·
930
· Лев Лукомський

Ruby Array tricks

  • Easily iterate through array of arrays:
[[:a, 100], [:b, 200]].each { |k, v| puts [k, v].inspect }
#=> [:a, 100]
#=> [:b, 200]
  • Combined lambda arguments:
{a: 100, b: 200}.each_with_object({}) { |(k, v), h| puts [k, v, h].inspect }
#=> [:a, 100, {}]
#=> [:b, 200, {}]
  • Convert hash to array with indexes:
{a: 100, b: 200}.map.with_index { |(k, v), i| [k, v, i] }
#=> [[:a, 100, 0], [:b, 200, 1]]
  • Mega-combined lambda arguments and with_index example:
{a: 100, b: 200}.each_with_object({}).with_index { |((k, v), h), i| puts [k, v, h, i].inspect }
#=> [:a, 100, {}, 0]
#=> [:b, 200, {}, 1]
  • Hide «unused variable» warning in IDE:
{a: 100, b: 200}.select { |_k, v| v == 200 }
  • Convert array of arrays to hash:
[[:a, 100], [:b, 200]].to_h
#=> {:a=>100, :b=>200}