I have this:
我有这个:
[["a3"], ["b3"], ["c7", "c9"]]
I need to remove the letter from the strings and convert them into integers. I need:
我需要从字符串中删除字母并将它们转换为整数。我需要:
[[3], [3], [7, 9]]
I tried:
我试过了:
[["a3"], ["b3"], ["c7", "c9"]].each do |a|
a.map do |string|
puts leave_num = string.slice!(0)
puts leave_num.to_i
end
end
but I am sure there is a nicer way.
但我相信有更好的方法。
3 个解决方案
#1
5
a = [["a3"], ["b3"], ["c7", "c9"]]
a.map { |r| r.map { |e| e[/\d+/].to_i } }
# => [[3], [3], [7, 9]]
#2
2
One way to do this can be:
一种方法是:
a = [["a3"], ["b3"], ["c7", "c9"]]
a.map { |b| b.map { |c| c.scan(/\d+/)[0].to_i }}
# => [[3], [3], [7, 9]]
Basically I'm going through each element and returning integers using regex.
基本上我正在浏览每个元素并使用正则表达式返回整数。
#3
1
You can use in your code:
您可以在您的代码中使用:
string[0] = ''
puts string # instead puts leave_num = string.slice!(0)
puts string.to_i # instead puts leave_num.to_i
another option:
另外一个选择:
a.map{|e| e.map{|n| n[1..-1].to_i}}
#=> [[3], [3], [7, 9]]
If your array elements has more letters like "d58as9a"
so for such case try this although @Amadan and @Shivam's answers are correct:
如果您的数组元素有更多的字母,如“d58as9a”,那么对于这种情况尝试这个虽然@Amadan和@ Shivam的答案是正确的:
a = [["a3"], ["b3"], ["c7", "c9"], ["d58as9a", "d5d54d"] ]
> a.map{|e| e.map{|n| n.scan(/\d/).join('').to_i}}
=> [[3], [3], [7, 9], [589, 554]]
Note: This will extract all digits from string.
注意:这将从字符串中提取所有数字。
#1
5
a = [["a3"], ["b3"], ["c7", "c9"]]
a.map { |r| r.map { |e| e[/\d+/].to_i } }
# => [[3], [3], [7, 9]]
#2
2
One way to do this can be:
一种方法是:
a = [["a3"], ["b3"], ["c7", "c9"]]
a.map { |b| b.map { |c| c.scan(/\d+/)[0].to_i }}
# => [[3], [3], [7, 9]]
Basically I'm going through each element and returning integers using regex.
基本上我正在浏览每个元素并使用正则表达式返回整数。
#3
1
You can use in your code:
您可以在您的代码中使用:
string[0] = ''
puts string # instead puts leave_num = string.slice!(0)
puts string.to_i # instead puts leave_num.to_i
another option:
另外一个选择:
a.map{|e| e.map{|n| n[1..-1].to_i}}
#=> [[3], [3], [7, 9]]
If your array elements has more letters like "d58as9a"
so for such case try this although @Amadan and @Shivam's answers are correct:
如果您的数组元素有更多的字母,如“d58as9a”,那么对于这种情况尝试这个虽然@Amadan和@ Shivam的答案是正确的:
a = [["a3"], ["b3"], ["c7", "c9"], ["d58as9a", "d5d54d"] ]
> a.map{|e| e.map{|n| n.scan(/\d/).join('').to_i}}
=> [[3], [3], [7, 9], [589, 554]]
Note: This will extract all digits from string.
注意:这将从字符串中提取所有数字。