Nirupa Nirupa - 2 years ago 107
Ruby Question

Cannot resolve if-else loop in Rails console (Rails Tutorial - Ch 4) (solved)

So I am new to Ruby on Rails and following Micheal Hartl's Rails Tutorial and this question is from Ch 4 where I am learning Rails console.

I am trying to execute following loop:

>> s = "foobar"
>> if s.nil?
>> "The variable is nil"
>> elsif s.empty?
>> "The string is empty"
>> elsif s.include?("foo")
>> "The string includes 'foo'"
>> end

Where according to book it should print:

=> "The string includes 'foo'"

But I am getting answer : nil

Now I have also tried to just the loop one by one (i.e. just if condition) then it works fine.

Tried several things as answered below but having same issue.

irb(main):095:0* if s.nil?
irb(main):096:1> return_value = "The variable is nil"
irb(main):097:1> elsif s.empty?
irb(main):098:1> return_value = "The string is empty?"
irb(main):099:1> elseif s.include?("foo")
irb(main):100:1> return_value = "The string has 'foo'"
irb(main):101:1> end
=> nil

All this time I was using "elseif" instead of "elsif"

Answer Source

I found the answer for this case:

elseif is not a correct branch command. So the code you are using actually intepreted as:

if s.nil?
  return_value = "The variable is nil"
elsif s.empty?
  return_value = "The string is empty?"
  elseif s.include?("foo")
  return_value = "The string has 'foo'"

Why it returns nil? Because the code actually falls into the else block as you see: not nil and not empty

Why elseif does not return error? Since Ruby uses lazy evaluation. The s.empty? return false, so it does not even try to execute the block in elsif. Then it cannot know if elseif function is predefined or not.

Is this understandable?

So the solution is very simple, correct elseif to elsif. Have fun!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download