有沒有辦法在方法中獲取參數名稱列表?如何獲取方法定義中的名稱或參數?
例如,假設我有以下方法定義:
def speak(name, age, address)
# some code
end
我怎樣才能得到的name
,age
和address
一個數組?
有沒有辦法在方法中獲取參數名稱列表?如何獲取方法定義中的名稱或參數?
例如,假設我有以下方法定義:
def speak(name, age, address)
# some code
end
我怎樣才能得到的name
,age
和address
一個數組?
您可以直接使用這些值。
def speak(name, age, address)
puts "Hello #{name}!"
end
要訪問你可以使用local_variables
的名字,但我真的不推薦它。
def speak(name, age, address)
p local_variables # => [:name, :age, :address]
end
但最有可能你會想使用哈希:
def speak(hash)
# use the keys/values of hash
end
現在你可以使用
speak({:name => "foo", :age => 42, :address => "123"})
# or
speak(:name => "foo", :age => 42, :address => "123")
找到了答案!
def speak (name, age, address)
puts local_variables
end
可以使用local_variables
它,但有一個更好的辦法:
def speak(name, age, address)
p self.method(__method__).parameters #=> [[:req, :name],
[:req, :age],
[:req, :address]]
end
當您使用local_variables
你應該在方法的開始使用它:
def speak(name, age, address)
foo = 1
p local_variables #=> [:name, :age, :address, :foo]
end
這是[有沒有辦法在ruby中返回方法參數名稱](http://StackOverflow.Com/q/2452077/#2452322),[在Ruby中反射方法參數](http:// StackOverflow的.com/q/3456827 /#3460072) ,[任何ruby庫檢查什麼是某些方法的參數?](http://StackOverflow.Com/q/6420695/#6425175)和[Ruby:如何檢查實例方法的參數而不創建新實例?](http://StackOverflow.Com/q/6717912/#6717939)。 –