我如何定义一个参数在 Ruby 中没有类型的方法 [英] How can I define a method which arguments have no type in Ruby

查看:14
本文介绍了我如何定义一个参数在 Ruby 中没有类型的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我定义了一个方法:

If I defined a method:

def weird_method(first_argument, second_argument)
  #code here
end

这样我就可以传递参数,例如:1, :digit, 'some', "more"(Fixnum, Symbol, String etc.) ,但是如果我只想传递这个: argument1, argument2 ,我的意思是没有类型并且看起来像局部变量但实际上不是的值.我怎样才能以某种方式接受它们并在方法体中使用它们?

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,当传递 blok 时,它可以在 .isntance_eval 中做那种事情

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

一切都可以在排球进一步的地方进行.我只是举了个例子.sum、play、swim、eat 是Something 类中定义的方法.

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.

推荐答案

符号的存在正是为了您在此处谈论的目的:它们是仅对自身进行评估的值.符号 :volleyball 就是符号 :volleyball,这就是它的全部.它没有其他价值或意义.

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 volleyball() :volleyball end).但这似乎不合时宜.

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 沿着 def method_missing(m, *args) 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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆