检查使用%w(),Ruby创建的数组中是否存在元素
我知道我可以使用 %w() 作为创建数组的快捷方式。例如,这些应该是等效的:
FOO = %w(dog, cat)
BAR = ["dog", "cat"]
FOO = %w(dog, cat)
BAR = ["dog", "cat"]
但是当我include用来检查这些数组中包含的内容时:
FOO = %w(dog, cat)
BAR = ["dog", "cat"]
puts FOO.include? "dog" #false
puts BAR.include? "dog" #true
第一个puts返回,false而第二个返回true。为什么会这样?
回答
不,这些数组不等价
但这些是
FOO = %w(dog cat) # note that the `%w` syntax doesn't need commas.
BAR = ["dog", "cat"]
也就是说,您的第一个版本不是FOO.include? "dog"因为它包含"dog,"和"cat"。