如何定义Ruby中没有类型的参数的方法

如果我定义了一个方法:

def weird_method(first_argument, second_argument) #code here end 

所以这样我可以传递如下参数:1,:digit,’some’,“more”(Fixnum,Symbol,String等),但是如果我想传递这个: argument1,argument2 ,我的意思是没有类型,看起来像局部变量,但它们实际上不是。 我怎么能以某种方式接受它们并在方法体中使用它们?

PS:我需要它来实现一个小的DSL,当blok通过时,它可以在.isntance_eval中做那种东西

 Something.with_method do sum 1, 2 #(I can implement it) play volleyball #(I can NOT implement it) swim further #(I can NOT implement it) eat "a lot" #(I can implement it) end 

编辑:

一切都可以继续排球 。 我只是举了一个例子。 sum,play,swim,eat是Something类中定义的方法。

符号存在的目的正是你在这里谈论的目的:它们是仅仅评估自己的价值观。 象征:volleyball是象征:volleyball ,这就是它将永远存在的一切。 它没有其他价值或意义。

如果你只是想让它以不同的方式阅读以达到审美目的,你最好的选择可能是定义返回相应符号的方法(例如def volleyball() :volleyball end )。 但这似乎是不合时宜的。

如果你真的希望人们能够发送任何不是方法的东西,你可以沿着def method_missing(m, *args) m.to_sym end的方式实现method_missing 。 但我真的觉得这个设计在我能想到的大多数情况下都很尴尬。

 class Something attr_reader :callstack def initialize @callstack = {} end def self.with_method &block self.new.instance_exec &block end def method_missing method, *params params.empty? ? method : callstack[method] = params end end Something.with_method do sum 1, 2 play volleyball swim further eat "a lot" puts callstack # => {:sum=>[1, 2], :play=>[:volleyball], :swim=>[:further], :eat=>["a lot"]} end 

这有帮助吗?

您必须将对象作为方法参数传递。 您尝试通过传递任意未定义的名称来实现什么function? 您始终可以将它们作为字符串传递,然后使用该字符串来使用方法内的文本。

恩。

 def self.methodname(arg1, arg2) arg1 = arg2 end Class.methodname("greeting","hello") 

将变量greeting设置为'hello'