Duck off
Published over 6 years ago

Let’s ignore the ducks.

def amazing(id)
  case id
  when :first    then "I am first!"
  when :all      then "All!"
  when Integer   then "That should just be fine"
  when String    then "No strings attached"
  when true      then "Fine. You are right"
  else raise "Stop being a jerk!"
  end
end

Oh! I love my ducks. Ducks are the ruby way! and only ruby way to do it. Fascism!

def amazing(id)
  case
  when id == :first  then "I am first!"
  when id == :all    then "All!"
  when id.respond_to?(:integer?) && id.integer? then "That should just be fine"
  when id.respond_to?(:to_str?) && id.to_str?   then "No strings attached"
  when id == true then "Fine. You are right"
  else raise "Stop being a jerk!"
  end
end

Ok. Get rid of naked “case” statement. No no, not facism. I’d say Ignorance

def amazing(id)
  if id == :first  then "I am first!"
  elsif id == :all    then "All!"
  elsif id.respond_to?(:integer?) && id.integer? then "That should just be fine"
  elsif id.respond_to?(:to_str?) && id.to_str?   then "No strings attached"
  elsif id == true then "Fine. You are right"
  else raise "Stop being a jerk!"
  end
end

Open question

Which way would you choose ? I’d choose the first one and I’d go even further to say that duck typing is over hyped and it all depends on the context where it’s being used. One really needs to have an open mind to accept that there are more than one ways to do it else you should be where you actually belong