Reputation: 5559
I am trying to look for and return a score between 0 and 10 in a string. message examples
"Toni gets 9"
"8 for Sam"
"10 is a reasonable score for Jed"
This is what I've tried:
message.split.find do |score|
(0..10).include? score.to_i
end
Upvotes: 1
Views: 105
Reputation: 41
You can do this:
message.split(' ')[1].scan(/\d/)
Or this:
message.gsub(/[^0-9]/, '')
Or you can use a loop:
message.each_char{ |c| if c.ord<11 or c.ord>0 }
Upvotes: 0
Reputation: 3356
Try this:--
messages = ["Toni gets 9",
"8 for Sam",
"10 is a reasonable score for Jed",]
irb> messages.collect{|msg| msg.split.find{|str| str.match /\b^(10|[0-9])\b/}}
=> ["9", "8", "10"]
Upvotes: 0
Reputation: 39365
You can try this one:
input = [ "0 Toni", "Toni gets 9", "8 for Sam", "10 is", "11 is" ]
input.each do |sentence|
if(sentence =~ /\b([0-9]|10)\b/)
puts sentence
end
end
I have used word boundary(\b
) around the regex so that it doesn't match any digits sticked with the text.
Upvotes: 0
Reputation: 19228
I'd do like this:
regexp = /\b(?:10|[0-9])\b/
'Toni gets 9'[regexp]
# => "9"
'8 for Sam'[regexp]
# => "8"
'10 is a reasonable score for Jed'[regexp]
# => "10"
'11 is my score'[regexp]
# => nil
'01 is your score'[regexp]
# => nil
'1000 is no score'[regexp]
# => nil
Upvotes: 2
Reputation: 18567
message.split.find { |string| (0..10).include?(string =~ /\A\d+\z/) }
Upvotes: 1
Reputation: 5905
a = ["8 out of gem", "ruby got 10", "ali receives 13 marks"]
a.each do |i|
if ((i =~ /\d/) > -1 && (i =~ /\d/) < 11)
puts i
end
end
Output:
8 out of gem
ruby got 10
Upvotes: 0