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"]
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With