Doubt in array method each_with_index

Asked

Viewed 124 times

2

When executing the method below it prints literally 0 x 2, 1 x 4. etc..

I need to find a solution to print only the result of the value product by the index.

My current code:

array = [2,4,6,8]

array.each_with_index {|value, index| puts "#{index} * #{value}"; } 

2 answers

3


He’s doing it because you’re telling him to do it.

Like the * is among "" he considers a string and not a mathematical operation.

One way to solve this is to put everything into one #{}, this is what the code looks like:

array = [2,4,6,8]

array.each_with_index {|value, index| puts "#{index * value}";} #aqui eu retirei um  }, # e o {

If you want to store the results in a array, for later uses, one of the ways to do this is like this:

array = [2,4,6,8]
otherArray = []

array.each_with_index {|value, index| otherArray[index] = index * value; } 

puts otherArray

See working on repl it. the two examples

  • Thanks for the answer, I have one more question for example I have this array from above that is doing this multiplication operation if I want to put the result #{index * value}";} in a new array, as I could do this?

  • see if this link help you.

  • If this answer solved your problem and there is no doubt left, mark it as correct/accepted by clicking on the " " that is next to it, which also marks your question as solved. If you prefer the other answer, you can mark it as correct/accepted, but only one answer can be marked this way, you can still click the arrow up if you liked the question, this is the way we say thanks here on the site. If you still have any questions or would like further clarification, feel free to comment.

  • I edited the answer by adding one of the ways to do this

  • Thank you for your help from the heart, for more people like Oce in the world

2

You are printing the "account" itself (and not the product result) because the terms are interpolated within a string:

puts "#{index} * #{value}"

It will print, for each iteration, the index value, followed by an asterisk between spaces, with the value at the end. You are not, in fact, evaluating the operands. In the above section, the * is not the multiplication operator, it is only a part of the string.

In this case as you only want the result, it makes no sense to use interpolation. Just print the result of the operation. So:

array = [2, 4, 6, 8]

array.each_with_index do |value, index|
  puts index * value
end

Above, the * is in fact playing the role of multiplier operator and therefore the product results will be correctly evaluated and printed.

Interpolation, therefore, would only make sense if you wanted to show each "armed account", followed by its respective result:

array = [2, 4, 6, 8]

array.each_with_index do |value, index|
  puts "#{index} * #{value} = #{index * value}"
end

See the two examples working on Repl.it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.