Skip to content

Instantly share code, notes, and snippets.

@emad-elsaid
Forked from padde/chained-comparison.rb
Created April 16, 2014 22:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emad-elsaid/10939640 to your computer and use it in GitHub Desktop.
Save emad-elsaid/10939640 to your computer and use it in GitHub Desktop.
# 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