Translate

September 24, 2013

Case equality operator === in ruby

To enable developers to write neat, compact code, Many classes take advantage of implementing their own versions of '==='. The '===’ operator is known as the case equality operator. The '===’ operator is used when testing cases in case statements.
def test_object number 
  case number
    when Fixnum
      case number 
        when 1  
          puts "It's One"
        when 2..10  
          puts "Between two and ten"
        else
          puts "-- #{number} -- is not between one and ten"
      end
    when String 
      puts "You passed a string"
    else "I have no idea what to do with -- #{number} --"
  end
end
for each 'when' statement the '===' operator is called on the when argument (1,2..10,String) and the case argument (number) is used for the comparison. For line 5 the comparison done shall be '1 === number'. For most classes ‘===’ is just an alias to ‘==’ however some classes redefine ‘===’ to allow for better functionality in case statements. In Ruby a Proc is a block of executable code, an anonymous function which can be passed around as if it were data. Like ‘===’, a Proc can map a number of arguments to either a true or false value.
is_weekday = lambda {|day_of_week, time| time.wday == day_of_week}.curry  
      
    sunday    = is_weekday[0]  
    monday    = is_weekday[1]  
    tuesday   = is_weekday[2]  
    wednesday = is_weekday[3]  
    thursday  = is_weekday[4]  
    friday    = is_weekday[5]  
    saturday  = is_weekday[6]  
      
    case Time.now  
    when sunday   
      puts "Day of rest"  
    when monday, tuesday, wednesday, thursday, friday  
      puts "Work"  
    when saturday  
      puts "Happy"  
    end  
Simple Factorial lambda function in Ruby
factorial = lambda do |n|
  n <= 1 ? 1 : (n * factorial.call(n - 1))
end

factorial.call 3

No comments: