Phoebe Turner
Phoebe Turner

Reputation: 3

multiply array using each on ruby

I've been stuck on this problem. I'd appreciate any help.

The instructions "Use the .each method on the odds array to print out double the value of each item of the array. In other words, multiply each item by 2.

Make sure to use print rather than puts, so your output appears on one line."

My code

odds = [1,3,5,7,9]

odds.each do |placeholder|
    odds *= 2
    print odds
end

Upvotes: 1

Views: 9310

Answers (5)

Ramana Javvaji
Ramana Javvaji

Reputation: 1

Here Iam done that on succesfully

odds = [1,3,5,7,9]
odds.each do |x|
    x *= 2
    print x
end

Upvotes: 0

Mircea
Mircea

Reputation: 10566

odds.each { |x| print "#{x*2}" }

ruby-ish way:

print odds.map {|x| x*2}.join(' ')

Upvotes: 3

Kaysser Kayyali
Kaysser Kayyali

Reputation: 1588

odds = [1,3,5,7,9]
odds.each do |placeholder|
  odds *= 2
  print odds
end

Your usage of #each is correct here, but remember that #each receives an ::Enumerable object, the block passed in uses the variable placeholder to encapsulate the value in the ::Array at the current point of the iteration. Therefore you would need to use placeholder to retrieve the value you want to double, and not odds because odds would still be an ::Array within the ::Enumerable function #each.

This code can be written in two lines as follows:

odds = [1,3,5,7,9]
odds.each {|placeholder| print placeholder * 2 }

Strictly speaking, #map would be the preferred method for doing this.

Upvotes: 5

kevinthompson
kevinthompson

Reputation: 574

odds is your array. placeholder represents a value from the array. Without explicitly providing you the answer, what you want to do is multiply the value by 2, not the array itself.

Upvotes: 0

Mike Manfrin
Mike Manfrin

Reputation: 2762

You are trying to multiply the Array odds by two in each iteration in your code. The do |placeholder| means 'for each item in the array, give me the single element and call it placeholder'.

So you would need to use placeholder *= 2.

However, since you aren't mutating the original value in odds, you can shorten your inner block by just print placeholder * 2.

Additionally, while the question might be saying to use :each, :map is much more canonical to what you are doing. Using map would allow you to double each element like so:

odds.map{ |i| i*2 }

Upvotes: 1

Related Questions