我有一个带有可选哈希的vararg的函数,可以作为最后一项传递:
def func(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
items = args
end
如果我有一个数组并想传递哈希值,我该如何调用此函数?
x = [ "one", "two", "three" ]
....
func(*x, :on => "yes") # doesn't work, i get SyntaxError
SyntaxError消息是:
syntax error, unexpected tSYMBEG, expecting tAMPER
fun(*x, :on => "yes")
我正在运行ruby v1.8.7。
答案 0 :(得分:1)
在第一个arg之前没有*
的情况下调用它。
def func(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
items = args
puts "Options: On: #{options[:on]}, Off: #{options[:off]}\n" if options.length > 0
p args
end
func(x, 123, 'a string', {:on => "yes", :off => "no"})
# Prints:
Options: On: yes, Off: no
[["one", "two", "three"], 123, "a string"]