Three integers are given separated by spaces. Output the value obtained by multiplying three integers.
For example
4 10 5
In this case 4 x 10 x 5
200
Please output.
ruby.rb
numbers = gets.split(' ').map(&:to_i)
a = 1
numbers.each do |number|
a = a * number
end
puts a
numbers = gets.split(' ').map(&:to_i)
・ Call the input element with the get method
-Split the character string separated by commas with the split method
・ Extract elements one by one with the map method and convert them to integers with to_i
a = 1
numbers.each do |number|
a = a * number
end
・ Substitute 1 for a at ʻa = 1` (initial value) ・ Substitute the elements of numbers into the number variable and repeat the process below.
numbers = gets.split(' ').map(&:to_i).inject(:*)
puts numbers
inject is a method that iterates like each and map.
The feature is that iterative calculations are performed using blocks.
Array object.inject {|initial value,element|Block processing}
It is described as.
The elements of the block are added by the array in the order of repetition, and the calculation is performed by processing the block.
You can write the inject more stylishly by passing the operator as a symbol to the inject.
For example
I want to calculate the total contents of the array
I want to calculate the value by multiplying all
I want to subtract in order using the contents of the array
It can be used in various situations such as *.
array = 1..6
p array.inject(:+) #Add all the elements of the array
p array.inject(3,:+) #Add all the elements of the array to the initial value of 3
p array.inject(:*) #Multiply all the elements of the array
p array.inject(3,:*) #Multiply all the elements of the array by the initial value of 3
p array.inject(100,:-) #Subtract the total value of array from 100
[Execution result]
21
24
720
2160
79
The method using the inject method pointed out in the comment is smarter and easier to calculate! Thank you for your comment.
Recommended Posts