Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Coercion in Ruby

Coercion in Ruby

Avatar for Grzegorz Witek

Grzegorz Witek

May 09, 2018
Tweet

More Decks by Grzegorz Witek

Other Decks in Technology

Transcript

  1. Strong vs. weak typing $> 3 + “a” Python: unsupported

    operand type(s) for +: 'int' and 'str' Ruby: String can't be coerced into Fixnum Javascript: “3a”
  2. Strong vs. weak typing $> 3 + “a” Python: unsupported

    operand type(s) for +: 'int' and 'str' Ruby: String can't be coerced into Fixnum Javascript: “3a”
  3. How do I Ruby? money = Money.new(3) money * 2

    # => 6 2 * money # => ERROR U FAIL
  4. Bad solution class Fixnum
 alias :old_multiply :* def *(val)
 if

    defined?(Money) && val.is_a?(Money)
 return self * val.amount
 else
 old_multiply(val)
 end
 end
 end
  5. Good solution class Money < Struct.new(:amount)
 
 def *(value)
 amount

    * value
 end def coerce(other) 
 [self, other]
 end end
  6. How does it work? Short answer: when Ruby can’t handle

    the param type, it calls arg.coerce(self) it gets 2 elements array, and calls array[0].method(array[1])
  7. How does it work? Fixnum#*(Money) => omg, what to do?

    Money#coerce => [Money, Fixnum] Money#*(Fixnum) => I know how to handle it!