0

Could you explain what the code below is doing:

resp = s3.list_buckets
puts resp.buckets.map(&:name)

My question is specific to map. I am not able to understand how map is being used here. Also, what does (&:name) mean?

I referred map documentation. However, I'm not able to correlate it with the map in the code above. Per the documentation, Map should be followed by a {}, but it is followed by a () in the code above.

In perl context, map will work on an array/list and will return a new array/list. So, it seems to be doing something similar here as well, but I cannot decode that.

Any pointers to documentation would be helpful.

sawa
  • 165,429
  • 45
  • 277
  • 381
slayedbylucifer
  • 22,878
  • 16
  • 94
  • 123

2 Answers2

2

map is an alias for collect

map(&:name) is shortcut for map {|x| x.name }

map expects a block. & calls to_proc on the object, and passes it as a block and Symbol has to_proc implemented. Refer docs for more info

Santhosh
  • 28,097
  • 9
  • 82
  • 87
1

& of (&:name) means what follows it should be a Proc object and will be converted to a code block.

Since & expects a Proc object, :name will be converted to a Proc object, this is done by calling :name.to_proc.

After :name is converted to a Proc object, & then converts the resulting Proc object to a code block and gives the code block to map.

In summary, there are totally two type conversions occured, one is converting a symbol to a Proc object, the other is converting a Proc object to a code block.

uncutstone
  • 408
  • 2
  • 11