How can I define a method which arguments have no type in Ruby [closed]

我怕爱的太早我们不能终老 提交于 2020-01-03 06:01:08

问题


If I defined a method:

def weird_method(first_argument, second_argument)
  #code here
end

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: 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

EDIT:

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.


回答1:


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.

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.

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.




回答2:


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

Does this help?




回答3:


You must pass objects as method arguments. What functionality are you trying to accomplish by passing arbitrary non-defined names? You could always pass them as a string and then use the string to use the text inside the method.

ex.

def self.methodname(arg1, arg2)
  arg1 = arg2
end

Class.methodname("greeting","hello")

would set the variable greeting equal to 'hello'



来源:https://stackoverflow.com/questions/21080780/how-can-i-define-a-method-which-arguments-have-no-type-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!