If I have this array:
["1","2","3,a","4,b"]
how can I get this array from it?
["1","2","3","4"].
If I have this array:
["1","2","3,a","4,b"]
how can I get this array from it?
["1","2","3","4"].
Assuming you have all integers, (If not I guess you get the idea :))
["1","2","3,a","4,b"].collect {|i| i.to_i}
With an array like:
ary = ["1","2","3,a","4,b"]
I'd use:
ary.map{ |s| s[/\A(\d+)/, 1] }
Which results in:
[ [0] "1", [1] "2", [2] "3", [3] "4" ]
It simply finds the numerics at the start of the strings and returns them in a new array.
Try:
["1","2","3,a","4,b"].map(&:to_i)
=> [1, 2, 3, 4]
to get array of strings
["1","2","3,a","4,b"].map(&:to_i).map(&:to_s)
=> ["1", "2", "3", "4"]
This should also works...
array=["1","2","3,a","4,b"]
for i in 0..array.length()-1
if array[i].include?(",")
ab=array[i].split(",")
array[i]=ab[0]
end
end
print array #["1","2","3","4"]
Try this delete option :
irb(main):014:0> a = ["101","2zd","3,a","10,ab"]
=> ["101", "2zd", "3,a", "10,ab"]
irb(main):015:0> count = a.count
irb(main):016:0> for i in 0..count
irb(main):017:1> puts a[i].delete("^0-9")
irb(main):018:1> end
101
2
3
10
UPDATED Code ( Use of Each Loop - Thanks to the Tin Man)
irb(main):005:0> a = ["101","2zd","3,a","10,ab"]
=> ["101", "2zd", "3,a", "10,ab"]
irb(main):006:0> b = []
=> []
irb(main):007:0> a.each do |t|
irb(main):008:1* b << t.delete("^0-9")
irb(main):009:1> end
=> ["101", "2zd", "3,a", "10,ab"]
irb(main):010:0> puts b
101
2
3
10
=> nil