What is Returned in Ruby if the Last Statement Evaluated is an If Statement
If your if
statement doesn't result in any code being run, it returns nil, Otherwise, it returns the value of the code that was run. Irb is a good tool to experiment with such stuff.
irb(main):001:0> i = if false then end
=> nil
irb(main):002:0> i = if true then end
=> nil
irb(main):007:0> i = if false then "a" end
=> nil
irb(main):008:0> i = if false then "a" else "b" end
=> "b"
What is the difference between if statements with then at the end?
then
is a delimiter to help Ruby identify the condition and the true-part of the expression.
if
condition then
true-part else
false-part end
then
is optional unless you want to write an if
expression in one line. For an if-else-end spanning multiple lines the newline acts as a delimiter to split the conditional from the true-part
# can't use newline as delimiter, need keywords
puts if (val == 1) then '1' else 'Not 1' end
# can use newline as delimiter
puts if (val == 1)
'1'
else
'Not 1'
end
Does ruby stop evaluating if statements when first condition is false?
Ruby, and most other programming languages use short circuiting boolean expressions. Meaning any expression of the form false && puts("hi")
will not run the right side of the expression puts("hi")
. This goes for if
conditions as well, anything with &&
really.
This is specially important to know because you always want to put faster or cheaper expressions/functions on the left side and more expensive expressions on the right side of a &&
operator.
Consider this
puts "hi" if expensive_method() && some_value
In the above example expensive_method
will always run. But what if some_value
is sometimes false? This would be more efficient:puts "hi" if some_value && expensive_method()
Taking advantage of the possibility that some_value
might sometimes be false, we spare ourselves from having to evaluate expensive_method
in those cases.In short, take advantage of boolean expression short circuiting.
https://en.wikipedia.org/wiki/Short-circuit_evaluation
Last expression evaluated in Ruby
Ruby's syntactic sugar for setter methods always returns the right side of the assignment, even if you do something else in your method. The Well-Grounded Rubyist puts it better than I could:
The Well-Grounded Rubyist - Chapter 3.3.3Setter methods don’t return what you might think. When you use
the syntactic sugar that lets you make calls to = methods that look like assignments,
Ruby takes the assignment semantics seriously. Assignments (like x = 1)
evaluate to whatever’s on their right-hand side. Methods usually return the
value of the last expression evaluated during execution. But = method calls
behave like assignments: the value of the expression ticket.price = 63.00 is
63.00, even if the ticket= method returns the string "Ha ha!". The idea is to
keep the semantics consistent. Under the hood, it’s a method call; but it looks
like an assignment and behaves like an assignment with respect to its value as
an expression.
ruby: return true or false based on condition inside method
You want something like this:
def method_name
total_value < item_value
end
Ruby will always return the value of the last evaluated statement in the function. what is the point of return in Ruby?
return
allows you to break out early:
def write_code(number_of_errors)
return "No problem" if number_of_errors == 0
badness = compute_badness(number_of_errors)
"WHAT?! Badness = #{badness}."
end
If number_of_errors == 0
, then "No problem"
will be returned immediately. At the end of a method, though, it's unnecessary, as you observed.Edit: To demonstrate that
return
exits immediately, consider this function:def last_name(name)
return nil unless name
name.split(/\s+/)[-1]
end
If you call this function as last_name("Antal S-Z")
, it will return "S-Z"
. If you call it as last_name(nil)
, it returns nil
. If return
didn't abort immediately, it would try to execute nil.split(/\s+/)[-1]
, which would throw an error.
Related Topics
How Can Multiple Trailing Slashes Can Be Removed from a Url in Ruby
Ruby How to Generate a Tree Structure Form Array
Include Module in All Minitest Tests Like in Rspec
Does The Rails Orm Limit The Ability to Perform Aggregations
How to Get Records Created at The Current Month
Running "Bundle Install" Fails and Asks Me to Run "Bundle Install"
Is The Assignment Operator Really "Just" an Operator
How Does String.Unpack Work in Ruby
Error Installing Ruby in Yosemite
Ruby Fails on Osx Lion with Rbenv
Where to Reopen a Class in Ror
Many to Many Table with an Extra Column in Rails
Error Installing Rdoc Documentation: Incompatible Encoding Regexp Match
Rails Has_Many Through Form with Additional Attributes
Is There a Command Line Framework for Ruby
Does Rails Support a Neat Way of Listening to a Udp Socket
Why Slicing The Params Hash Poses a Security Issue on Mass-Assignment