apdm apdm - 5 months ago 11
Ruby Question

When using IRB, what is the significance of the left side of the => operator?

I was testing the

method to try and better understand it. I was using IRB in my command line to test it, using the example provided in the ruby documentation:

a = "cruel world"
a.scan(/(.)(.)/) {|x,y| print y, x }


Should return:

rceu lowlr


Well, when I ran it, it did return
rceu lowlr=> "cruel world"
:

$ irb
irb(main):001:0> a = "cruel world"
=> "cruel world"
irb(main):002:0> a.scan(/(.)(.)/) {|x,y| print y, x }
rceu lowlr=> "cruel world"
irb(main):003:0>


Usually when use IRB, the left side of the
=>
is blank, and the right side is the returned value. In this case, the left side is the returned value...and the right side is just...what the return value would be if it was spelled correctly? Why?

Answer

The => indicates the return value of whatever code you just ran. That is, if I set

b = a.scan(/(.)(.)/) {|x,y| print y, x }

then the value of b would be cruel world. The reason it doesn't appear on a new line is that print doesn't automatically add a new line at the end of whatever it prints to the screen. If you use puts instead of print you'll see that each character appears on its own line, and => "cruel world" appears at the bottom on its own line.

Comments