2

我正在 Ruby 中进行一些 Watir-webdriver 测试,但似乎无法使以下代码正常工作。我想将一个可选validation参数传递给该log_activity方法。

def log_activity (type, *validation)
    #do something
end

我将以下参数传递给该方法:

log_activity("license", 1)

我希望validation == 1是真的,但它是假的:

puts validation.empty?
-> false

puts validation
-> 1

if validation == 1
    puts "validation!!!!"
else
    puts "WTF"
end
-> WTF

我究竟做错了什么?

忘了提,我使用的是 ruby​​ 1.9.3

4

3 回答 3

3

*validation是一个包含第二个和所有参数的数组。鉴于它是一个数组,您看到的结果是有意义的。您想检查 *validation 数组中的第一个元素。

Alternatively, if you will only get one optional argument, you can do:

def log_activity (type, validation=nil)
    #do something
end

Then validation will be whatever you passed in.

于 2012-09-11T17:12:31.193 回答
1

Read "Method Arguments In Ruby" and look at "Optional Arguments". I found it pretty handy.

I am pasting the useful content:

Optional Arguments

If you want to decide at runtime how many – if any – arguments you will supply to a method, Ruby allows you to do so. You need to use a special notation when you define the method, e.g.:

def some_method(*p)
end

You can call the above method with any number of arguments (including none), e.g.:

some_method

or

some_method(25)

or

some_method(25,"hello", 45, 67)

All of those will work. If no arguments are supplied, then p will be an empty array, otherwise, it will be an array that contains the values of all the arguments that were passed in.

于 2012-09-11T17:36:08.337 回答
0

当您使用 *args 作为 Ruby 中的最后一个参数时,args 是一个数组。

不幸的是,在 Ruby 1.8 上,array.to_s == array.join("")

尝试任一

if validation == [1]

或者

if validation.first == 1
于 2012-09-11T17:11:13.000 回答