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}
Written by Lev Lukomsky
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#