Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add 1 only to Integers in an array in ruby

I have an array which contains mixed classes:

arr = ["I", "have", 2, "dimes", "and" , 3, "nickels"]

How do I perform addition on the integers in the array without modifying the strings?

The expected output is,

["I", "have", 3, "dimes", "and" , 4, "nickels"]
like image 232
Jason Matney Avatar asked Dec 12 '25 23:12

Jason Matney


1 Answers

def add_to_integers(ary, n)
  ary.map { |i| i.is_a?(Integer) ? (i + n) : i }
end

add_to_integers([1, 'foo'], 1)
# => [2, "foo"]
like image 111
toro2k Avatar answered Dec 15 '25 14:12

toro2k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!