Skip to content

Instantly share code, notes, and snippets.

@padde
Created April 20, 2012 15:45
Show Gist options
  • Save padde/2429814 to your computer and use it in GitHub Desktop.
Save padde/2429814 to your computer and use it in GitHub Desktop.
chained comparison in Ruby
# Chained comparisons in Ruby
# inspired by http://coffeescript.org/#comparisons
# as well as http://refactormycode.com/codes/1284
[:<, :>, :<=, :>=].each do |operator|
[Float, Fixnum, Rational, Comparable].each do |klass|
klass.class_eval do
alias_method "_#{operator}", operator
define_method operator do |rhs|
send("_#{operator}", rhs) && rhs
end
end
end
FalseClass.class_eval do
define_method(operator){|rhs| false }
end
end
if __FILE__ == $0
(1..15).each do |x|
case
when x <= 5
puts "#{x} is too low"
when 5 < x <= 7
puts "#{x} is low but ok"
when x == 8
puts "#{x} is exactly right"
when 8 < x <= 10
puts "#{x} is high but ok"
when x > 10
puts "#{x} is too high"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment