Confusion with Array#map

Hi could anyone help me how does the below concept helped to produce the
output?

%w{ david black }.map(&:capitalize)
#=> [“David”, “Black”]

map iterates through the given array and collects the results with a
block executed on them, in this case interpreting the argument symbol
:capitalize into a proc { |s| s.capitalize }

Joel P. wrote in post #1103136:

map iterates through the given array and collects the results with a
block executed on them, in this case interpreting the argument symbol
:capitalize into a proc { |s| s.capitalize }

How proc object is getting called by call to produce the output? Who
is calling that?

On Mon, Mar 25, 2013 at 1:37 PM, Love U Ruby [email protected]
wrote:

Joel P. wrote in post #1103136:

map iterates through the given array and collects the results with a
block executed on them, in this case interpreting the argument symbol
:capitalize into a proc { |s| s.capitalize }

How proc object is getting called by call to produce the output? Who
is calling that?

The operator “&” is the block operator, which is turning the symbol
:capitalize which refers to the method capitalize in that context.
Since at that point, map is sending in strings, it says to call the
capitalize method on that string.
https://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Method_Calls#The_Ampersand_Operator

The below code giving empty array.

[2,3][-1,0]
#=> []

But why does the code below giving nil value?

[2,3][0,-1]
#=> nil

[start, size]

Think about the size -1 -

What exactly would an array with -1 members look like?

What would an array with 0 members look like?

John

On Mon, Mar 25, 2013 at 7:41 PM, tamouse mailing lists
[email protected] wrote:

On Mon, Mar 25, 2013 at 1:37 PM, Love U Ruby [email protected] wrote:

How proc object is getting called by call to produce the output? Who
is calling that?

The operator “&” is the block operator, which is turning the symbol
:capitalize which refers to the method capitalize in that context.
Since at that point, map is sending in strings, it says to call the
capitalize method on that string.

https://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Method_Calls#The_Ampersand_Operator

The crucial bit here is that Symbol#to_proc exists. Actually anything
can be used in that way:

irb(main):001:0> o = Object.new
=> #Object:0x802bdf10
irb(main):002:0> def o.to_proc; lambda {|x| “<#{x.inspect}>”}
irb(main):003:1> end
=> nil
irb(main):004:0> (1…5).map(&o)
=> ["<1>", “<2>”, “<3>”, “<4>”, “<5>”]

Cheers

robert

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs