Search code examples
rubystringsubstring

Quick way to extract a substring from a string in Ruby using any method


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'


Solution

  • If you can guarantee that the first - appears following your desired substring, Ruby’s string split method is a good candidate for this. This’d look something like:

    string1.split('-')[0]