I have tried
STDIN.gets.chomp.split(" ")
And then converted each elements in the array to Integer.
But I believe there should be a better solution.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Assuming the integers cannot be negative:
Or for arbitrary input:
The key here is using using
Array#mapto invoke a block for each value in the array, creating a new array of the results for each. Then we useSymbol#to_proc(invoked by the ampersand syntax of Ruby) to tersely invoke theto_imethod on each string.For example,
foo.map(&:to_i)is equivalent tofoo.map{ |o| o.to_i }.Edit: it will be slightly faster to map the array in place, and split only on a single space if you know that is the only separator, and to not use Symbol#to_proc:
However, you are unlikely to see more than a very minor improvement here. Are you certain that you need this faster? What is your data, and what are your profiling results showing that this is a critical place where you need more speed?