Problem with return value

Hi
In this code :

···

-------------------------------

def test_method(name)
puts name
3+5
end

return_value = test_method("James")
puts return_value
-------------------------------

why when the last statement executed , "puts" does not return "nil" and
return 8?
--
Posted via http://www.ruby-forum.com/.

Because in Ruby, the last statement executed in a block is the block's value. That goes for your test_method's return value, and any other type of block you use.

···

On 06/08/2010 17:23, Amir Ebrahimifard wrote:

Hi
In this code :
-------------------------------

def test_method(name)
  puts name
  3+5
end

return_value = test_method("James")
puts return_value
-------------------------------

why when the last statement executed , "puts" does not return "nil" and
return 8?

--
Matthew Bloch

irb(main):001:0> def test_method(name)
irb(main):002:1> rv = puts(name)
irb(main):003:1> 3+5
irb(main):004:1> rv
irb(main):005:1> end
=> nil
irb(main):006:0> return_value = test_method("James")
James
=> nil
irb(main):007:0> puts return_value
nil
=> nil

···

On Fri, Aug 6, 2010 at 12:23 PM, Amir Ebrahimifard <amiref@ymail.com> wrote:

def test_method(name)
puts name
3+5
end

return_value = test_method("James")
puts return_value
-------------------------------

why when the last statement executed , "puts" does not return "nil" and
return 8?

Actually, 3+5 is the last statement in your test_method. Are you surprised that the value is 8?

-Rob

Rob Biedenharn
Rob@AgileConsultingLLC.com http://AgileConsultingLLC.com/
rab@GaslightSoftware.com http://GaslightSoftware.com/

···

On Aug 6, 2010, at 12:27 PM, Matthew Bloch wrote:

On 06/08/2010 17:23, Amir Ebrahimifard wrote:

Hi
In this code :
-------------------------------

def test_method(name)
puts name
3+5
end

return_value = test_method("James")
puts return_value
-------------------------------

why when the last statement executed , "puts" does not return "nil" and
return 8?

Because in Ruby, the last statement executed in a block is the block's value. That goes for your test_method's return value, and any other type of block you use.

--
Matthew Bloch