-9

If I have this array:

["1","2","3,a","4,b"]

how can I get this array from it?

["1","2","3","4"].
Greg
  • 9,068
  • 6
  • 49
  • 91
Aurick
  • 321
  • 1
  • 8

5 Answers5

9

Assuming you have all integers, (If not I guess you get the idea :))

["1","2","3,a","4,b"].collect {|i| i.to_i}
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
sameera207
  • 16,547
  • 19
  • 87
  • 152
3

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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
1

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"]
shweta
  • 8,019
  • 1
  • 40
  • 43
0

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"]
ѕтƒ
  • 3,547
  • 10
  • 47
  • 78
-2

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
Rubyist
  • 6,486
  • 10
  • 51
  • 86