As a beginner in Ruby, is there a quick to extract the first and second number from this string 5.16.0.0-15
? In this case, I am looking 5
and 16
. Thanks
CodePudding user response:
One way is to use the method String#match with the regular expression
rgx = /(\d )\.(\d )/
to construct a MatchData
object. The regular expression captures the first two strings of digits, separated by a period. The method MatchData#captures is then use to extract the contents of capture groups 1 and 2 (strings) and save them to an array. Lastly, String#to_i is used to convert the strings in the array to integers:
"5.16.0.0-15".match(rgx).captures.map(&:to_i)
#=> [5, 16]
We see that
m = "5.16.0.0-15".match(rgx)
#=> #<MatchData "5.16" 1:"5" 2:"16">
a = m.captures
#=> ["5", "16"]
a.map(&:to_i)
#=> [5, 16]
a.map(&:to_i)
can be thought of as shorthand for a.map { |s| s.to_i }
.
We can express the regular expression in free-spacing mode to make it self-documenting:
/
( # begin capture group 1
\d # match one or more digits
) # end capture group 1
\. # match a period
( # begin capture group 2
\d # match one or more digits
) # end capture group 2
/x # invoke free-spacing regex definition mode
CodePudding user response:
Use #split
, telling it to split on "."
and only split into three parts, then access the first two.
irb(main):003:0> s = "5.16.0.0-15"
=> "5.16.0.0-15"
irb(main):004:0> s.split(".", 2)
=> ["5", "16"]
Optionally map to integers.
irb(main):005:0> s.split(".", 2).map(&:to_i)
=> [5, 16]