2013-05-11 133 views
22

我想下面的符號字符串數組的元素轉換,並將其輸出如何將字符串數組轉換爲符號數組?

strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"] 

看看我在做什麼:

strings.each { |x| puts x.to_sym } 

沒有成功。我究竟做錯了什麼?

+2

可能重複的http://stackoverflow.com/questions/800122/best-way-to-convert-strings-to-symbols-in-hash – 2013-05-12 00:00:19

+0

@Abe:這是一個哈希鍵。這是數組元素。 – icktoofay 2013-05-12 00:04:13

+0

@Abe這不是一個dup,它是用於散列。 (編輯:icktoofay打敗我吧:P) – Doorknob 2013-05-12 00:04:57

回答

43

使用map而不是each

>> strings.map { |x| x.to_sym } 
=> [:HTML, :CSS, :JavaScript, :Python, :Ruby] 

對Ruby 1.8.7及更高版本或使用的ActiveSupport包括在內,你可以使用這個語法:

>> strings.map &:to_sym 
=> [:HTML, :CSS, :JavaScript, :Python, :Ruby] 

的原因,你的each方法似乎不工作是調用puts並用符號輸出符號的字符串表示形式(即沒有0​​)。此外,你只是循環和輸出的東西;你實際上並沒有構建一個新的數組。

2

@icktoofay有正確的答案,但只是爲了幫助你更好地理解each方法,在這裏是如何使用each做同樣的事情:

strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"] 
symbols = [] # an empty array to hold our symbols 
strings.each { |s| symbols << s.to_sym } 
4

icktoofay already gave the correct answer.

在附加備註:用

strings.map { |x| x.to_sym } 

你得到一個新的數組,原始數組不變。

要使用它,你可以把它分配給另一個變量:

string2 = strings.map { |x| x.to_sym } 

如果要修改字符串,你可以使用map!

strings.map! { |x| x.to_sym } 
9

我會做這樣的事情

strings.map! &:to_sym 
-1

或者可以做如下:

strings.each do |s| 
symbols.push(s.to_sym) 
15

清潔單行:

%w(HTML CSS JavaScript Python Ruby).map(&:to_sym) 

&告訴參數應被視爲一個塊,即建立陣列和應用to_sym到每個元素。

+0

你的回答是最乾淨的,我也對它進行了基準測試,並檢查了它在不同類型陣列上的性能。 我不確定是否最好給你一個基於你的新答案或只編輯這一個。 – Lomefin 2016-07-09 00:37:22

1

@ CB24的回答通常是最appropiate,我想比較與另一個

strings.collect {|x| x.to_sym } 

我做了一些基準和@ CB24的回答最適合在大多數情況下,當有一些元素的解決方案該數組,但如果碰巧是一個非常小的數組,collect方法工作得更快一點。

我在這裏發佈的代碼和結果,這是我真正的第一個基準,所以如果我有一些錯誤的一些反饋將不勝感激。我做了兩個字符串 - >符號與象徵 - >字符串

n = 1000000 

a = [:a,:b,:c,:d,:e,:f,:g,:h,:i].freeze #A "long" array of symbols 

Benchmark.bm do |x| 
    x.report { n.times { a.map(&:to_s)} } 
    x.report { n.times { a.collect{|x| x.to_s}} } 
end 

     user  system  total  real 
    2.040000 0.010000 2.050000 ( 2.056784) 
    2.100000 0.010000 2.110000 ( 2.118546) 


b = [:a, :b].freeze #Small array 

Benchmark.bm do |x| 
    x.report { n.times { b.map(&:to_s)} } 
    x.report { n.times { b.collect{|x| x.to_s}} } 
end 


     user  system  total  real 
    0.610000 0.000000 0.610000 ( 0.622231) 
    0.530000 0.010000 0.540000 ( 0.536087) 



w = %w(a b).freeze #Again, a small array, now of Strings 
Benchmark.bm do |x| 
    x.report { n.times { w.map(&:to_sym)} } 
    x.report { n.times { w.collect{|x| x.to_sym}} } 
end 

     user  system  total  real 
    0.510000 0.000000 0.510000 ( 0.519337) 
    0.440000 0.010000 0.450000 ( 0.447990) 



y = %w(a b c d e f g h i j k l m n o p q).freeze #And a pretty long one 
Benchmark.bm do |x| 
    x.report { n.times { y.map(&:to_sym)} } 
    x.report { n.times { y.collect{|x| x.to_sym}} } 
end 

     user  system  total  real 
    2.870000 0.030000 2.900000 ( 2.928830) 
    3.240000 0.030000 3.270000 ( 3.371295) 

拐點我沒有計算,但它是很有趣的,我聽說了一些改進,其中短陣列,因爲大多數的製造,他們只是一些元素。

相關問題