2

我有一个函数,它接受一个带有可选散列的可变参数,可以作为最后一项传递:

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。

4

1 回答 1

1

*在第一个参数之前调用它。

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"]
于 2012-09-08T00:26:06.940 回答