Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

empty condition in elsif section

Tags:

ruby

Can you explain what expression use ruby in "elsif" if expression is empty ?

arg = 3
if (arg == 1)
  puts "1"
elsif (arg == 2)
  puts "2"
elsif
  puts "3"
end

p (1...10).map { |i|
  if (i == 1)
    1
  elsif (i == 2)
    2
  elsif
    3
  end
}

Script output:

3
[1, 2, nil, nil, nil, nil, nil, nil, nil]
like image 781
Sergey Beduev Avatar asked Jan 17 '26 18:01

Sergey Beduev


1 Answers

Basically there is more to say:

In if-else branching, whenever any match condition has been found,then last statement of the matched clause has been returned by the if-else block. consider the below:

arg = 4
p m = if (arg == 1)
   "1"
elsif (arg == 3)
   "3"
elsif (arg ==4)
   "5";"11"
elsif
   "3"
end

output:

#11

But during matching with each clause if any bare elsif found then if-else block checks the truth value of its immediate expression and returned the value accordingly:

arg = "4"
p m = if (arg == "1")
   47
elsif 
   10 ; "7" 
elsif (arg =="5")
   12;14
elsif
   2
end

Output:

#"7"

Below code will return nil as nothing to return as 10 is used as condition checking,after that nothing in the code. so nil has been returned.

arg = "4"
p m = if (arg == "1")
   47
elsif 
   10 
elsif (arg =="5")
   12;14
elsif
   2
end  #nil

another code below to make things finally clear:

arg = "4"
p m = if (arg == "1")
   47
elsif 
   nil 
elsif (arg =="5")
   12;14
elsif
   2 ; "44"
end  #44

With all examples said,above I hope the reason is clear why - the below code outputs: [1, 2, nil, nil, nil, nil, nil, nil, nil]

p (1...10).map { |i|
  if (i == 1)
    1
  elsif (i == 2)
    2
  elsif
    3
  end
}

To answer your first code,first take a look at the below two:

m = if puts "hi"
p "hello"
end #"hi"

"hi" is printed as puts returns nil on which if clause evaluated to false thus hello is not printed. But the below code does as p is used there and if clause got executed on the p return value which is true.

m = if p "hi"
p "hello"
end 

#"hi"
#"hello"

Now hope you understood why 3 is coming as output from the below code,from the above all logic applied as a whole:

arg = 3
if (arg == 1)
  puts "1"
elsif (arg == 2)
  puts "2"
elsif
  puts "3"
end
like image 173
Arup Rakshit Avatar answered Jan 20 '26 15:01

Arup Rakshit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!