Reputation: 13
I want to grab a number from a list of scores e.g. "Score:5"
or "Score:10"
.
I can't find a way to grab the number and turn it into an int so I can use it for an array. Any help?
My code as follows looks for a score that contains a number
range = 0
array = []
Dir["C:/Users/Cam/Desktop/warmup/Warmup_tally/*"].each do |filename|
File.open(filename) do |f|
f.each_line do |line|
if line.include? "Score"
puts line.split(':')
range += 1
array.push(-0, "#{line}")
end
end
end
end
but I want to only grab that number and put it inside Array
.
Upvotes: 0
Views: 67
Reputation: 6064
Let's assume your array is
a=["Score:5","Score:10","Score:11"]
Code
p a.map{|x| x[/\d+/].to_i}
output
[5, 10, 11]
Update
I have taken your inner code and corrected it
if line.include? "Score"
array.push line[/\d+/].to_i
end
Or
array.push line[/\d+/].to_i if line.include? "Score"
Now print the array, output contains only the score numbers.
Upvotes: 4
Reputation: 15492
Could you just split on the :
character? Something like this:
prefix, score = "Score:5".split(':')
# => ["Score", "5"]
Then you could just do score.to_i
if you need it to be an integer.
Upvotes: 2