Skip to content

Instantly share code, notes, and snippets.

@MelanieS
Created December 17, 2012 22:07
Show Gist options
  • Save MelanieS/4322766 to your computer and use it in GitHub Desktop.
Save MelanieS/4322766 to your computer and use it in GitHub Desktop.
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
@migane
Copy link

migane commented Dec 19, 2012

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

@kotp
Copy link

kotp commented Dec 19, 2012

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

@DouglasAllen
Copy link

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