我怎么可以定义哪些参数具有在Ruby中没有类型的方法 [英] How can I define a method which arguments have no type in Ruby
问题描述
如果我定义了一个方法:
If I defined a method:
def weird_method(first_argument, second_argument)
#code here
end
所以这样我可以传递参数,如:1,:数字,某些,多(Fixnum对象,符号,字符串等),但如果我想通过眼前这个:参数1,参数2 ,我的意思是没有类型,看起来像局部变量的值,但它们实际上并非如此。我怎么能以某种方式接纳他们,并在方法体中使用它们?
so this way I can pass arguments like : 1, :digit, 'some', "more"(Fixnum, Symbol, String etc.) , BUT what If I wanted to pass just this: argument1, argument2 , I mean values that have no type and look like local variables but they actually are not. How can I accept them somehow and use them in the method body?
PS:我需要实现一个小的DSL,可以做这样的东西在 .isntance_eval 当BLOK传递
PS: I need it for implementing a small DSL that could do that kind of stuff in the .isntance_eval when blok is passed
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
编辑:
一切娓娓道来的排球和进一步的。安迪。我只是举了一个例子。总之,玩,游,吃的都是在东西类中定义的方法。
Everything could go on the palce of volleyball and further. I am just gave an example. sum, play, swim, eat are methods defined in the Something class.
推荐答案
符号整整你在谈论这里的目的存在:他们只是评估自己的值。符号:排球
是符号:排球
,这是所有它永远不会。它没有其他的价值和意义。
Symbols exist for exactly the purpose you're talking about here: They're values that just evaluate to themselves. The symbol :volleyball
is the symbol :volleyball
and that is all it will ever be. It has no other value or meaning.
如果您只是希望它以不同的阅读审美目的,最好的办法可能会是定义返回相应的符号方法(如 DEF排球():排球结束
)。但这似乎unidiomatic。
If you just want it to read differently for aesthetic purposes, your best bet would probably be to define methods that return the appropriate symbol (e.g. def volleyball() :volleyball end
). But this seems unidiomatic.
如果你真的希望人们能够发送几乎任何东西,是不是已经是一个方法,你可以实现一个的method_missing
沿<$ C $的线C> DEF的method_missing(男,*参数)m.to_sym结束。不过,我真的觉得这个设计在大多数情况下尴尬的我能想到的。
If you really want people to be able to send just about anything that isn't already a method, you could implement a method_missing
along the lines of def method_missing(m, *args) m.to_sym end
. But I really find this design awkward in most contexts I can think of.
这篇关于我怎么可以定义哪些参数具有在Ruby中没有类型的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!