How can I define a method which arguments have no

2019-06-11 12:16发布

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.

3条回答
贪生不怕死
2楼-- · 2019-06-11 12:27
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?

查看更多
ゆ 、 Hurt°
3楼-- · 2019-06-11 12:39

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.

查看更多
干净又极端
4楼-- · 2019-06-11 12:39

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'

查看更多
登录 后发表回答