Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.