4 ms·
Just a reminder of duck typing: Haskell style => function applied to parameter, e.g f(x) Ruby duck type style => parameter applies function to itself e.g x.f()
by yb66 14y ago
Just a reminder of duck typing:
Haskell style => function applied to parameter, e.g f(x)
Ruby duck type style => parameter applies function to itself e.g x.f()
An example:
module Dialable
def dial
# do stuff with self
puts "Dialling..."
end
end
# I wouldn't do this, but...
class String
include Dialable
end
# So, phone number as a string can be dialled
my_phone_number = "01 23 45678"
my_phone_number.dial
Dialling...
# I'd rather do this
class PhoneNumber < String
include Dialable
end
my_phone_number = PhoneNumber.new "01 23 45678"
my_phone_number.dial
Dialling...
# now you get an error on non phone number strings
"just a random string".dial
NoMethodError: undefined method `dial' for "just a random string":String
my_phone_number == "01 23 45678"
=> true
my_phone_number == "just a random string"
=> false
You get all the regex and string functions for free too.
- frio 14y agoAh, I see. I don't really know what's idiomatic in Ruby anymore; I haven't used it in anger for nigh on 5 years now :).