您的位置:首页 > 其它

Array of Strings to Convert to Mixed Array

2014-06-27 21:13 357 查看
I'm trying to convert an Array of Arrays consisting of Ruby Strings into an Array of Arrays consisting of Strings and Floats.

Here is my attempt:

array = [["My", "2"], ["Cute"], ["Dog", "4"]]
array.collect! do |x|
x.each do |y|
if y.gsub!(/\d+/){|s|s.to_f}
end
end
end

=> [["My", "2.0"], ["Cute"], ["Dog", "4.0"]]

I'm looking for this to rather return 
[["My",
2.0], ["Cute"], ["Dog", 4.0]]
 What did I do wrong?

What you did wrong is that you used 
gsub!
.
That takes a string and changes the string. It doesn't turn it into anything else, no matter what you do (even if you convert it to a float in the middle).

A simple way to achieve what you want is:

[["My", "2"], ["Cute"], ["Dog", "4"]].map{|s1, s2| [s1, *(s2.to_f if s2)]}

If you do not want to create the element array, but replace its contents, then:

[["My", "2"], ["Cute"], ["Dog", "4"]].each{|a| a[1] = a[1].to_f if a[1]}

If the numerical strings appear in random positions, then:

[["My", "2"], ["Cute"], ["Dog", "4"]]
.each{|a| a.each.with_index{|e, i| a[i] = a[i].to_f if a[i] and a[i] =~ /\d+/}}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: