Created
December 17, 2012 22:07
-
-
Save MelanieS/4322766 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if rocks > pebbles | |
puts "You have more rocks than pebbles." | |
elsif rocks < pebbles | |
puts "You have more pebbles than rocks." | |
end | |
if rocks > pebbles | |
puts "You have more rocks than pebbles." | |
elsif pebbles > rocks | |
puts "You have more pebbles than rocks." | |
end |
I'm more comfortable with logical operations, but specifically here I will do this with ternary operator:
gravel = [[1,3],[4,2],[6,6]]
gravel.each do |rocks,pebbles|
answer = rocks > pebbles ? ["more", "than"] : (rocks == pebbles ? ["as many","as"] : ["less","than"])
puts "You have " + answer[0] + " rocks " + answer[1] + " pebbles."
end
You may also if you prefer have an intermediate variable if you want to return the whole answer:
gravel = [[1,3],[4,2],[6,6]]
gravel.each do |rocks,pebbles|
element = rocks > pebbles ? ["more", "than"] : (rocks == pebbles ? ["as many","as"] : ["less","than"])
answer = "You have " + element[0] + " rocks " + element[1] + " pebbles."
puts answer
end
I like the ternary operator.
But really there is one operator that matches the situation perfectly, and that is the equality operator, AKA the spaceship operator.
gravel = [[1, 3], [4, 2], [6, 6]].
equality = {-1 => ['less', 'than'], 0 => ['as many', 'as'], 1 => ['more', 'than']}
gravel.each do |rocks, pebbles|
puts "You have %s rocks %s pebbles." % equality[rocks <=> pebbles]
end
I like fruit better. Who wants to eat gravel? sol ;-)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In answer to CodeGurl's Blog
The
elsif
will raise an eyebrow, as it is used as a second conditional test, not the more appropriateelse
if there are only two possible results. In this case, with the other option of there being an equal amount, theelsif
fits well, when you add theelse
statement and result.I have dried it a bit and left the output as the last thing I want to do, rather than conditionally outputting to the screen. If I wanted to conditionally print as well, then it would be fine there, but in this case, it is something you are always doing, so to reduce later edits, if you decide not to puts the string, you only have one place to make a change.
But, and I think this is your question, I also prefer to have the greater than symbol in both places and the subject swap. To me it is clearer. After reading the
if
, I don't have to switch logic, I just change subjects. It is more of a visual change and less likely to be missed if I am scanning code.But, I did fixate on the elsif at first, as it seemed out of place, without the third possibility.