请解释为什么[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
答案 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