Reputation: 25
I'm struggling with something I'm working on:
puts "What are your test scores?"
test_scores = gets.chomp.to_a
Basically I want to get the user's test scores, add them together and divide by the number of scores they give. I know I can use length
to see the number of tests scores in the array and inject(:+)
to add the numbers within the array, but what if the user doesn't use a comma to separate the grades?
test_scores = [90 87 07]
I can't use inject
without commas in place so how would I add the commas in between the numbers if the user doesn't? And then how do I keep from adding the commas if the user already has them in place?
Upvotes: 1
Views: 87
Reputation: 118261
How about this ?
puts "What are your test scores?"
test_scores = gets.scan(/\d+/).map(&:to_i)
puts test_scores.inject(:+)/test_scores.size
Now I am running the code :-
arup@linux-wzza:~/Ruby> ruby -v test.rb
ruby 2.0.0p451 (2014-02-24 revision 45167) [i686-linux]
What are your test scores?
12 33 12
19
arup@linux-wzza:~/Ruby> ruby -v test.rb
ruby 2.0.0p451 (2014-02-24 revision 45167) [i686-linux]
What are your test scores?
12,34 66
37
arup@linux-wzza:~/Ruby>
Upvotes: 2