Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return string until matched string in Ruby

Tags:

string

ruby

How do you return the portion of a string until the first instance of " #" or " Apt"?

I know I could split the string up into an array based on "#" or "Apt" and then calling .first, but there must be a simpler way.

like image 646
Doug Avatar asked Sep 23 '11 03:09

Doug


People also ask

What does =~ mean in Ruby?

=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.

What does split return in Ruby?

Syntax: arr = str.split(pattern, limit) public. Parameters: arr is the list, str is the string, pattern is the either string or regExp, and limit is the maximum entries into the array. Returns: Array of strings based on the parameters.

Can you index a string in Ruby?

index is a String class method in Ruby which is used to returns the index of the first occurrence of the given substring or pattern (regexp) in the given string. It specifies the position in the string to begin the search if the second parameter is present. It will return nil if not found.

How do you find a substring in a string in Ruby?

The string. index() method is used to get the index of any character in a string in Ruby. This method returns the first integer of the first occurrence of the given character or substring.


3 Answers

String splitting is definitely easier and more readable that a regex. For regex, you would need a capture group to get the first match. It will be the same as string splitting

string.split(/#|Apt/, 2).first
like image 169
bash-o-logist Avatar answered Oct 13 '22 12:10

bash-o-logist


I'd write a method to make it clear. Something like this, for example:

class String
    def substring_until(substring)
        i = index(substring)
        return self if i.nil?
        i == 0 ? "" : self[0..(i - 1)]
    end
end
like image 40
Dan Tao Avatar answered Oct 13 '22 12:10

Dan Tao


Use String#[] method. Like this:

[
  '#foo',
  'foo#bar',
  'fooAptbar',
  'asdfApt'
].map { |str| str[/^(.*)(#|Apt)/, 1] } #=> ["", "foo", "foo", "asdf"]
like image 30
Victor Deryagin Avatar answered Oct 13 '22 11:10

Victor Deryagin