检查使用 %w(), Ruby 创建的数组中是否存在元素

Ada*_*dam 1 ruby

我知道我可以使用 %w() 作为创建数组的快捷方式。例如,这些应该是等效的:

FOO = %w(dog, cat)
BAR = ["dog", "cat"]
Run Code Online (Sandbox Code Playgroud)

但是当我include用来检查这些数组中包含的内容时

FOO = %w(dog, cat)
BAR = ["dog", "cat"]

puts FOO.include? "dog" #false
puts BAR.include? "dog" #true
Run Code Online (Sandbox Code Playgroud)

第一个puts返回,false而第二个返回true。为什么会这样?

spi*_*ann 5

不,这些数组不等价

FOO = %w(dog, cat)
BAR = ["dog", "cat"]
Run Code Online (Sandbox Code Playgroud)

但这些是

FOO = %w(dog cat)       # note that the `%w` syntax doesn't need commas.
BAR = ["dog", "cat"]
Run Code Online (Sandbox Code Playgroud)

也就是说,您的第一个版本不是FOO.include? "dog"因为它包含"dog,""cat"