Shunan
Shunan

Reputation: 3254

How to multiply each number in array by 2 in ruby

I have an array with characters, numbers and float values.

 a[] = {'a',2,2.5}

I have to multiply each integer and float by 2 and no operation should be done on character.

My solution -

def self.double_numbers(input)
        input.map do |input_element|
            if input_element.is_a? Integer
                input_element.to_i * 2
            elsif input_element.is_a? Float
                input_element.to_Float * 2
            end
        end
    end

It is not working, for input

   a[] = {'a',2,2.5}

It is returning

0 4 4

Upvotes: 2

Views: 3679

Answers (2)

Sebastián Palma
Sebastián Palma

Reputation: 33420

You could use map and over each element in the array check if is Numeric, and if so, then multiply it by 2, then you can compact your result for nil values:

p ['a', 2, 2.5].map{|e| e * 2 if e.is_a? Numeric}.compact
# => [4, 5.0]

If you want to leave the elements which won't be applied the *2 operation, then:

p ['a', 2, 2.5].map{|e| e.is_a?(Numeric) ? e * 2 : e}

Also you could use grep to simplify the checking, and then map your only-numeric values:

p ['a', 2, 2.5].grep(Numeric).map{|e| e*2}
# => [4, 5.0]

I don't know the side effects of doing this, but looks good (of course if the output won't be only Numeric objects):

class Numeric
  def duplicate
    self * 2
  end
end

p ['a', 2, 2.5].grep(Numeric).map(&:duplicate)

Or also:

p ['a', 2, 2.5].grep(Numeric).map(&2.method(:*))
# [4, 5.0]

Upvotes: 8

Gagan Gami
Gagan Gami

Reputation: 10251

I have to multiply each integer and float by 2 and no operation should be done on character.

here you go:

> a = ["a", 2, 2.5]
> a.map{|e| e.is_a?(Numeric) ? e * 2 : e}
#=> ["a", 4, 5.0]

Note: a[] = {'a',2,2.5} not a correct syntax for array.

Upvotes: 2

Related Questions