Question about the evaluation of x = 'foo' if false


A

Aníbal Rojas

Hello,

I am kind of lost with the nil result while I am expecting a false:

irb(main):001:0> x = 'foo' if false
=> nil
irb(main):002:0> x
=> nil
irb(main):003:0> x = 'foo' if true
=> "foo"
irb(main):004:0> x
=> "foo"

Thanks in advance for sharing your knowledge,
 
Ad

Advertisements

C

Chris Hulan

Hello,

   I am kind of lost with the nil result while I am expecting a false:

irb(main):001:0>  x = 'foo' if false
=> nil
irb(main):002:0> x
=> nil
irb(main):003:0>  x = 'foo' if true
=> "foo"
irb(main):004:0> x
=> "foo"

   Thanks in advance for sharing your knowledge,

See http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UH
'if' doesn't return the logical value it evaluates, it returns the
value of the last statement
executed, in the false case nothing is executed, and nil is Ruby's
nothing value

Cheers
 
M

Mark Thomas

Hello,

   I am kind of lost with the nil result while I am expecting a false:

irb(main):001:0>  x = 'foo' if false
=> nil
irb(main):002:0> x
=> nil
irb(main):003:0>  x = 'foo' if true
=> "foo"
irb(main):004:0> x
=> "foo"

   Thanks in advance for sharing your knowledge,


Another way to think about it is that the above constructs are
alternate ways of expressing the following:

if false then x = 'foo' end
if true then x = 'foo' end

-- Mark.
 
Ad

Advertisements

A

Aníbal Rojas

Thanks for your responses!

--
Aníbal

Another way to think about it is that the above constructs are
alternate ways of expressing the following:

iffalse then x = 'foo' endiftrue then x = 'foo' end

-- Mark.
 

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

Top