2017-03-10 60 views
-2

請解釋爲什麼[s1]會從文檔中返回此示例中的預期行爲,但[s2]不會返回類似結果?#assoc對使用%w初始化的數組無效,爲什麼?

#!/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

%w notation預計項目由平原空間分開:

# s2 = %w(letters, a, b, c) # WRONG 
    s2 = %w(letters a b c) # CORRECT 
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 
+2

沒有必要正確答案複製粘貼到你的。我沒有計劃將其刪除。 – mudasobwa