Reputation: 719
I have a Ruby string variable with the value 1.14.2.ab3-4.dl0.rhel
However, I want to discard everything after the second decimal so that I get the value as 1.14
I am using the following command:
str.split(".")[0]
but it doesn't seem to work
Upvotes: 1
Views: 79
Reputation: 110755
@maxple's answer only works when the substring of interest is at the beginning of the string. As that was not part of the specification (only in the example), I don't think that's a reasonable assumption. (@Eric did not make that assumption.)
There is also ambiguity about your statement, "discard everything after the second decimal". @maxple interpreted that as after the second decimal point (but also discarded the second decimal point), whereas @Eric assumed it meant after the second decimal digit. This is what happens when questions are imprecise.
If the substring is at the beginning of the string, and you mean to discard the second decimal point and everything after, here are two ways to do that.
str = "1.14.2.ab3-4.dl0.rhel"
1. Modify @Eric's regex:
str[/\A\d+\.\d+/]
#=> "1.14"
2. Convert the string to a float and then back to a string:
str.to_f.to_s
#=> "1.14"
#1 returns nil
if the desired substring does not exist, whereas #2 returns "0.0"
. As long as "0.0"
is not a valid substring, either can be used to determine if the substring exists, and if it does, return the substring.
Upvotes: 1
Reputation: 1658
You could also use the partition method in String: https://ruby-doc.org/core-2.2.0/String.html#method-i-partition
"1.14.2.ab3-4.dl0.rhel".partition(/\d+\.\d{2}/)[1]
=> "1.14"
Upvotes: 0
Reputation: 54303
With a regexp, you could just look for the first number with 2 decimals :
"1.14.2.ab3-4.dl0.rhel"[/\d+\.\d{2}/]
#=> "1.14"
Upvotes: 2
Reputation: 26788
When you split by .
on your string you get:
['1', '14', '2', 'ab3-4', 'dl0', 'rhel']
From this you can get the first two items joined by period:
str.split(".")[0..1].join(".")
# or
str.split(".").first(2).join(".")
Upvotes: 3