It's almost the same in Ruby. You can use the same regular expression. You
use the match method to match a string against a regular expression. And,
then you use the method to pick match elements by their 1-based-index (1
for name and 2 for price). Finally, the integer is converted from a String
to an Integer using the to_i method.
#match (or any other regexp operator) populates the special variable $~, which is an array where element 0 contains the entire matched portion of the input, and elements 1..n contain the capture groups. This is often the best approach if you want to extract a number of fields from a single string.
Here is another approach:
puts "Name: #{str[/(.+)\s+(\d+)/, 1]}"
str[regexp, pos] is equivalent to "str.match(regexp) ; $~[pos]" and is nicely expressive when you only have one capture group that you’re interested in.
IRB is your friend here — it provides a nice REPL environment where you can quickly see the effect of one or more lines of code.
Enjoy!
···
On Apr 15, 2022, at 7:45 PM, wilson <info@bigcount.xyz> wrote:
Hello
sorry I am ruby newbie. I want to ask a question on regex to extract values from a string and maybe types transformation is required.
for instance the string: "black berry 12".
I want go get the name: black berry [String]
the price: 12 [Int]
I did this in other language such as java/scala:
> val regex = """(.+)\s+(\d+)""".r
val regex: scala.util.matching.Regex = (.+)\s+(\d+)
> str match {
> case regex(name,price) => (name,price.toInt)
> }
val res2: (String, Int) = (black berry,12)
But sometimes for a simple task it's not convenient to write a java program.
so what's the ruby solution?
#match (or any other regexp operator) populates the special variable $~, which is an array where element 0 contains the entire matched portion of the input, and elements 1..n contain the capture groups. This is often the best approach if you want to extract a number of fields from a single string.
Here is another approach:
puts "Name: #{str[/(.+)\s+(\d+)/, 1]}"
str[regexp, pos] is equivalent to "str.match(regexp) ; $~[pos]" and is nicely expressive when you only have one capture group that you’re interested in.