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.
=~ 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.
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.
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.
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.
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
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
Use String#[] method. Like this:
[
'#foo',
'foo#bar',
'fooAptbar',
'asdfApt'
].map { |str| str[/^(.*)(#|Apt)/, 1] } #=> ["", "foo", "foo", "asdf"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With