i } ) } end...">

Ruby range. Hash battery reduction

I have this method

def heights
  (60..68).reduce({}) { |h, i| h.merge!( { %(#{i/12}'#{i%12}") => i } ) }
end

it returns a hash of heights

{
  "5'0\"" => 60, "5'1\"" => 61, "5'2\"" => 62,
  "5'3\"" => 63, "5'4\"" => 64, "5'5\"" => 65,
  "5'6\"" => 66, "5'7\"" => 67, "5'8\"" => 68
}

What I want. However, I do not like to use the method merge!. I would prefer to use the syntax hash[key] = valuefor assignment:

def heights
  (60..68).reduce({}) { |h, i| h[%(#{i/12}'#{i%12}")] = i }
end

But this code is causing errors. I know that with a decrease in your pipes you can name your battery and cell.

I also understand that

sum = 0
(1..5).each { |i| sum += i }

equivalently

(1..5).reduce(0) { |sum, i| sum + i }

So why is this

hash = {}
(1..5).each { |i| hash[i.to_s] = i }

work the same way

(1..5).reduce({}) { |hash, i| hash["#{i}"] = i }
+4
source share
2 answers

The unit reducemust return a new battery. In your case

(1..5).reduce({}) { |hash, i| hash["#{i}"] = i }

block i, , [] . :

(1..5).reduce({}) { |hash, i| hash["#{i}"] = i; hash }
+3

each_with_object reduce:

(60..68).each_with_object({}) { |i, h| h[%(#{i/12}'#{i%12}")] = i }

enumerable.each_with_object(obj) { ... } obj, ; h , reduce.

, reduce.

+6

Source: https://habr.com/ru/post/1660742/


All Articles