Implementing chained comparisons in Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
(1..10).each do |x| case when x < 3 puts "#{x} is quite low" when 3 <= x < 6 puts "#{x} is quite all right" when 6 <= x < 10 puts "#{x} is quite fine" when 10 <= x puts "#{x} is quite high" end end lets BEGIN { Object.send(* "ZGVmaW5lX21ldGhvZA=bWV0aG9kX21pc3Npbmc=".unpack("mm" ) ){|*|} [[],[61]].inject([]){|_,__|_<<[60,*__]<<[62,*__]}.map{|_|_.pack("c*" )}. each { |a| [Float, Fixnum, Comparable].each { |b| b.class_eval { c = instance_method(a) and define_method(a) { |d| c.bind(self).call(d) and d } there } is } no ;FalseClass.class_eval "def %s(*) false end"%a } END {} to this madness } this is RUBY! (not perl?)
Refactorings
No refactoring yet !
Burke Libbey
May 4, 2010, May 04, 2010 13:11, permalink
I love the use of UnboundMethod. I'm going to have to remember that one.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
[:<, :>, :<=, :>=].each do |operator| [Float, Fixnum, Comparable].each do |klass| klass.class_eval { alias_method("__#{operator}__", operator) define_method(operator) do |operand| send("__#{operator}__", operand) and operand end } end FalseClass.send(:define_method, operator) { false } end (1..10).each do |x| case when x < 3 puts "#{x} is quite low" when 3 <= x < 6 puts "#{x} is quite all right" when 6 <= x < 10 puts "#{x} is quite fine" when 10 <= x puts "#{x} is quite high" end end
Tried to port some Perl code, but I'm not quite sure if it's Rubyish enough…