#assoc对使用%w初始化的数组不起作用,为什么?

时间:2017-03-10 06:48:52

标签: ruby

请解释为什么[s1]会从文档中返回此示例中的预期行为,但[s2]不会返回类似的结果?

#!/usr/bin/env ruby

s1 = [ "colors", "red", "blue", "green" ]
s2 = %w( letters, a, b, c )
s3 = "foo"

a = [ s1, s2, s3 ]

puts a.assoc "colors"
msg = a.assoc("colors").nil? ? "value is nil" : "value is true"
puts msg

puts a.assoc "letters"
msg = a.assoc("letters").nil? ? "value is nil" : "value is true"
puts msg

产地:

colors
red
blue
green
value is true

value is nil

2 个答案:

答案 0 :(得分:2)

%w notation期望项目由普通空格分隔:

# s2 = %w( letters, a, b, c ) # WRONG
  s2 = %w( letters a b c )    # CORRECT

答案 1 :(得分:0)

您的s2数组变量

中有一些不必要的逗号
s2 = %w( letters, a, b, c )

所以你的a数组变量数组看起来像

[["colors", "red", "blue", "green"], ["letters,", "a,", "b,", "c"], "foo"]

因此,a.assoc "letters,"应该有效

puts a.assoc "letters,"
msg = a.assoc("letters,").nil? ? "value is nil" : "value is true"
puts msg

产地:

letters,
a,
b,
c
value is true

但是,mudasobwa's answer是正确的

  

%w notation期望项目由普通空格分隔:

# s2 = %w( letters, a, b, c ) # WRONG
  s2 = %w( letters a b c )    # CORRECT