Split a value and units in Ruby
What is the most elegant way to split a value and units, so you have:
13min.some_method["value"] = 13
13min.some_method["unit"] = "min"
I think it should use unpack or spli开发者_运维问答t, but I can get it to work!
How about String#scan:
>> "13min".scan(/\d+|[^\d]+/)
=> ["13", "min"]
Another way:
>> i = "13min" =~ /[^\d]/
=> 2
>> "13min"[0,i]
=> "13"
>> "13min"[i,"13min".length]
=> "min"
The reason String#split isn't the best is because it gets rid of the delimiter, but your two strings are butted up against each other.
Here's an alternative you could try (which will also work with floats and negative numbers):
s = "-123.45min"
value = s.to_f # => -123.45
unit = s[/[a-zA-Z]+/] # => "min"
Like Ruby's to_f
and to_i
method, it will just "try" to get a result. So if you don't provide a unit, unit
will be nil
- if you only provide a unit, value will be 0.
"123-34min" value = 123, unit = "min"
"min" value = 0 unit = "min"
"-1234" value = -1234 unit = nil
"123-foo-bar" value = 123 unit = "foo"
P.S. Of course this assumes that you don't have any numbers in your unit.
精彩评论