Skip to content

Instantly share code, notes, and snippets.

@rwz
Last active April 26, 2017 19:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rwz/c166ebaaacd78a92125fc2c490c9552a to your computer and use it in GitHub Desktop.
Save rwz/c166ebaaacd78a92125fc2c490c9552a to your computer and use it in GitHub Desktop.
dynamic method definition in ruby
class MyClass
def static_yield(*)
yield if block_given?
end
define_method :dynamic_yield do |*|
yield if block_given?
end
define_method :dynamic_yield_fix do |*, &block|
block&.call
end
end
MyClass.new.static_yield { puts "Now you see me!" } # => Now you see me!
MyClass.new.dynamic_yield { puts "Now you don't!" } # => nil ಠ_ಠ
MyClass.new.dynamic_yield_fix { puts "This works though." } # => This works though.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment