Help me understand this SIMPLE Ruby code, using puts in a def

F

Fily Salas

Hi,

I was practicing ruby and accidentally came across something that got me
thinking (nothing important but I want to know why).

Why does the example-1 works and not example-2, if all I'm doing is
moving the puts?

Example-1:
def message
"this is working"
end
puts message.upcase


Example-2:
def message
puts "this is working"
end
message.upcase

Can someone explain this a little bit? I could just ignore it but I
would like to know the reason.

Thanks
 
S

Sam Duncan

This is where irb is handy. The short of it is that in your first
example a string is returned on which you call upcase. In your second
example the thing returned is the result of puts, which is nil.
ruby-1.9.2-p0 > foo = puts 'foo'
foo
=> nil
ruby-1.9.2-p0 > foo
=> nil
ruby-1.9.2-p0 > foo.upcase
NoMethodError: undefined method `upcase' for nil:NilClass

Does that help?

Sam
 
R

Roger Braun

Hi Fily

2011/4/27 Fily Salas said:
Hi,

I was practicing ruby and accidentally came across something that got me
thinking (nothing important but I want to know why).

Why does the example-1 works and not example-2, if all I'm doing is
moving the puts?

Example-1:
def message
=C2=A0"this is working"
end
puts message.upcase


Example-2:
def message
=C2=A0puts "this is working"
end
message.upcase

Can someone explain this a little bit? I could just ignore it but I
would like to know the reason.

The return value of the "puts" method is always nil, not the string it
prints. What your second example does is try to invoke the "upcase"
method on nil.

--=20
Roger Braun
rbraun.net | humoralpathologie.de
 
C

Cee Joe

I agree with Sam:
THIS IS WORKING
=> nil
this is working
nil <----- extra nil
=> nil

Since the nil is the last thing that is read in the method, upcase is
called on that nil and upcase throws an error b/c you can't use that
method on a nil. Make sense?

-Cee
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top