简体   繁体   English

字符串数组转换为混合数组

[英]Array of Strings to Convert to Mixed Array

I'm trying to convert an Array of Arrays consisting of Ruby Strings into an Array of Arrays consisting of Strings and Floats. 我试图将由Ruby字符串组成的数组数组转换为由字符串和浮点数组成的数组数组。

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? 我正在寻找它来返回[["My", 2.0], ["Cute"], ["Dog", 4.0]]我做错了什么?

What you did wrong is that you used gsub! 您做错的是您使用了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+/}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM