Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify method default argument using define_method?

Tags:

ruby

define_method could be used to define methods:

define_method(:m) do |a|
end

which is equivalent to the following:

def m(a)
end

However, what is the equivalent form of the following using define_method:

def m(a=false)
end

Note that I'd need to be able to call m() without giving any argument.

like image 671
bryantsai Avatar asked Jan 12 '10 06:01

bryantsai


2 Answers

This actually just works like you would expect in Ruby 1.9!

define_method :m do |a = false|
end

If you need 1.8 compatibility, but you don't necessarily need a closure to define your method with, consider using class_eval with a string argument and a regular call to def:

class_eval <<-EVAL
  def #{"m"}(a = false)
  end
EVAL

Otherwise follow the suggestion in the thread that philippe linked to. Example:

define_method :m do |*args|
  a = args.first
end
like image 86
molf Avatar answered Sep 23 '22 00:09

molf


This is currently not possible due to the yacc parser. This thread on Ruby-forum proposes several solutions.

class A
     define_method(:hello) do | name, *opt_greeting|
        option = opt_greeting.first || Hash.new
        greeting = option[:greeting] || "hello"
        puts greeting+" "+name
     end
end


a = A.new
a.hello "barbara"
a.hello "Mrs Jones", :greeting => "Good Morning"
like image 41
philant Avatar answered Sep 22 '22 00:09

philant