Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save pinzolo/3971315 to your computer and use it in GitHub Desktop.
Save pinzolo/3971315 to your computer and use it in GitHub Desktop.
define_methodでデフォルト値のある引数を持つメソッドを定義する
class Test
def self.method_missing(name, *args)
klass = class << self; self end
klass.class_eval do
define_method(name) do |a = 1, b = 2|
puts "a: #{a}, b: #{b}"
end
end
if args.length > 1
__send__(name, args[0], args[1])
elsif args.length == 1
__send__(name, args[0])
else
__send__(name)
end
end
end
Test.hoge("A", "B")
# => "a: A, b: B"
Test.hoge("C")
# => "a: C, b: 2"
Test.hoge
# => "a: 1, b: 2"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment