如何将字符串数组转换为符号数组?
我想下面的符号字符串数组的元素转换,并将其输出如何将字符串数组转换为符号数组?
strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]
看看我在做什么:
strings.each { |x| puts x.to_sym }
没有成功。我究竟做错了什么?
使用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)。此外,你只是循环和输出的东西;你实际上并没有构建一个新的数组。
@icktoofay有正确的答案,但只是为了帮助你更好地理解each
方法,在这里是如何使用each
做同样的事情:
strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]
symbols = [] # an empty array to hold our symbols
strings.each { |s| symbols << s.to_sym }
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 }
我会做这样的事情
strings.map! &:to_sym
或者可以做如下:
strings.each do |s|
symbols.push(s.to_sym)
清洁单行:
%w(HTML CSS JavaScript Python Ruby).map(&:to_sym)
&
告诉参数应被视为一个块,即建立阵列和应用to_sym
到每个元素。
你的回答是最干净的,我也对它进行了基准测试,并检查了它在不同类型阵列上的性能。 我不确定是否最好给你一个基于你的新答案或只编辑这一个。 – Lomefin 2016-07-09 00:37:22
@ 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)
拐点我没有计算,但它是很有趣的,我听说了一些改进,其中短阵列,因为大多数的制造,他们只是一些元素。
可能重复的http://stackoverflow.com/questions/800122/best-way-to-convert-strings-to-symbols-in-hash – 2013-05-12 00:00:19
@Abe:这是一个哈希键。这是数组元素。 – icktoofay 2013-05-12 00:04:13
@Abe这不是一个dup,它是用于散列。 (编辑:icktoofay打败我吧:P) – Doorknob 2013-05-12 00:04:57