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:
I'm looking for this to rather return
What you did wrong is that you used
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:
If you do not want to create the element array, but replace its contents, then:
If the numerical strings appear in random positions, then:
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+/}}
相关文章推荐
- Convert array of key value object to object of the key values (ruby)
- 4、Write a function to find the longest common prefix string amongst an array of strings
- How to get the length of array of strings in C? - Yahoo! Answers
- Conversion of C++/CLI array of strings to native C++ char**
- Write a function to find the longest common common string amongst an array of strings.
- Write a function to find the longest common prefix string amongst an array of strings.
- Sorting a mixed array of hashes and strings
- Insight into DOMDocument - how to convert data from XML to array in PHP
- Call C# Code from C++ and read an array of struct which contains strings
- .net array convert to class String
- Select n numbers from 1 to m with all of array 'all' and none of array 'none'
- Creating one array of strings in c fails ,why?
- convert from to (byte [] array)
- [转载]:How to pass a list of values or array to SQL Server stored procedure?
- Java: convert a file to a byte array, then convert byte array to a file.
- Spring-aop: Error Cannot convert value of type [$Proxy...] to required type
- Failed to convert property value of type [java.lang.String] to required type [boolean] for property
- Convert a byte array to a Hex string
- xml Convert To ArrayCollection
- 各种类型to array of bytes