Nirupa Nirupa - 2 months ago 5
Ruby Question

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

I'm following Micheal Hartl's Rails Tutorial and this question is from Chapter 4.

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


According to book it should print:

=> "The string includes 'foo'"


But I am getting answer :
nil


Now I have also tried the branches one by one (i.e. just if conditions) then it works fine.

Tried several things as answered below but having same issue.

> 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'"
> end
=> nil


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

Answer

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'"
end

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!