Home > Software engineering >  Quick way to extract a substring from a string in Ruby using any method
Quick way to extract a substring from a string in Ruby using any method

Time:11-03

As a beginner in Ruby, how can I extract a substring from within a string in Ruby?

Example:

string1 = "1.1.67.01-f9@92a47088f49d095f0"

I want to extract substring from the beginning to '-'. So the substring is '1.1.67.01'

CodePudding user response:

one way with regex

outcome = string1.match(/^(.*)\-/) { $1 }
puts outcome if outcome
=> "1.1.67.01"

CodePudding user response:

Sounds like a job for a quick-and-dirty regex.

string1 = "1.1.67.01-f9@92a47088f49d095f0"
/^([^-]*)-/ =~ string1
puts $1

Let's break down the regular expression

/^([^-]*)-/

The / are the quotation marks of regex, sort of like " are for strings. Inside the regex, ^ marks the start of the string and - is a literal dash (which terminates our match in this case). Then we have a capture group (...), which indicates that that's the part of the match we're actually interested in. Inside, we match any character that is not a dash ([^-]), repeated zero or more times (*).

After a successful match, we print the first (and, in our case, only) capture group $1.

  • Related