Skip to content

Instantly share code, notes, and snippets.

@pcalcado
Created December 21, 2011 21:11
Show Gist options
  • Save pcalcado/1507722 to your computer and use it in GitHub Desktop.
Save pcalcado/1507722 to your computer and use it in GitHub Desktop.
ruby is inconsistent
#given
def store_for_later(something_i_can_invoke)
@something_i_can_invoke = something_i_can_invoke
end
#i want
SomeCommonCode = lambda { :bazinga }
store_for_later(SomeCommonCode)
@something_i_can_invoke.call
#to be the same as
store_for_later { :ohYeah }
@something_i_can_invoke.call
#and while we are here, duck typing should mean i can also do
class Invokable
def call
:yay
end
end
store_for_later(Invokable.new)
@something_i_can_invoke.call
#i can solve this with
def store_for_later(something_i_can_invoke=nil, &block)
@something_i_can_invoke = block_given? ? block : something_i_can_invoke
end
#and that's what stuff like event machine do:
# https://github.com/eventmachine/eventmachine/blob/master/lib/eventmachine.rb#L169
# because ruby is terribly inconsistent when it comes to lambdas
# but most classes won't comply with this, like this classic:
[1,2,3].map { |i| i + 10 }
# => [11, 12, 13]
modifier = lambda { |i| i + 10 }
[1,2,3].map(modifier)
# => ArgumentError: wrong number of arguments(1 for 0)
from (irb):223:in `map'
from (irb):223
from /Users/pcalcado/.rvm/rubies/ruby-1.9.2-p290/bin/irb:16:in `<main>'
# this makes working with functions and callbacks in ruby frustrating =/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment