简体   繁体   中英

map with two block variables - ruby

I came across a weird behaviour in Ruby that I can't explain.

If we have an array of arrays and wanted to iterated over it with map . I tried to use map with two block variables expecting the second one to be the index, but it instead takes the values of the inner array. Why?

persons = [["john", 28], ["mary", 25],["emma", 30]]
persons.map do |param1, param2|
  puts param1
  puts param2
end

The output is

john
28

So how come that it takes the values of the iterators it should iterate over?

This is what you are looking for:

persons.map.with_index do |array, index|
  ...
end

You can pass an offset if you want the index to start in 1 instead of 0: with_index(1)

You're using map but you don't seem to care about the result, so each is more appropriate. Unlike in JavaScript where you may be expecting an index to appear by default, in Ruby you have to ask for it.

If you wanted to display the values you'd do something like this:

persons.each_with_index do |(name, age), index|
  puts '%d. %s (%s)' % [ index + 1, name, age ]
end

Note the use of (name, age) to unpack what is otherwise a pair of values that would be received as an array. This is because each -type methods treat arrays as singular objects. In the default case it'll auto-unpack for you.

If you wanted to transform the values then you'd use map :

persons.map.with_index do |(name, age), index|
  '%d. %s (%s)' % [ index + 1, name, age ]
end

Remember, when using map you must capture as a variable, return it, or somehow use the result or it will get thrown away.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM