How do I remove the first occurence of a substring in string? - ruby-on-rails

How can I remove the first occurence of a given substring?
I have:
phrase = "foobarfoo"
and, when I call:
phrase.some_method_i_dont_know_yet ("foo")
I want the phrase to look like barfoo.
I tried with delete and slice but the first removes all the occurrences but the second just returns the slice.

Use sub! to substitute what you are trying to find with ""(nothing), thereby deleting it:
phrase.sub!("foo", "")
The !(bang) at the end makes it permanent. sub is different then gsub in that sub just substitutes the first instance of the string that you are trying to find whereas gsub finds all instances.

sub will do what you want. gsub is the global version that you're probably already familiar with.

Use the String#[] method:
phrase["foo"] = ""
For comparison, in my system this solution is 17% faster than String#sub!

Related

Difficulty applying a Regex to a Rails View. Should I make it a helper method?

I am trying to apply the following regex to one of my views:
^([^\s]+)\s+
This is to remove any string of consecutive non-whitespace characters including any white space characters that follow from the start of the line (remove everything except the first word). I have input it on Rubular and it works.
I was wondering how I would be able to apply it to my rails project. Would I create a rails helper method? So far I have tested it in irb and it is not returning the right value:
I would like to know how I can fix my method and if making it a helper method is the right approach. Thank you very much for your help guys!
The =~ operator matches the regular expression against a string, and it returns either the offset of the match from the string if it is found, otherwise nil.
You could either try it with String.match and work with the match data.
like
str.match(^([^\s]+)\s+)
or you don't use regex for readability. Split the string on spaces and return and array of the words and take the first one, like:
str.split(' ').first

Problems with a include or if in rails

Im having issues with rails with the code
if #turno.chop == res[:department].to_s
where turno contains strings like ABC1 and department like ABC, im trying to filter if turno its equal of department but i need reduce the string of turno for that.
Every time what i try to do that the code dont finish and stuck in other part of code, when i delete the condition, the code works perfectly but dont do the filter.
i tryid to to do like
if #turno.include?(res[:department].to_s)
But appears the same error.
I believe something very similar to this was answered in the stackoverflow.com question. How to check whether a string contains a substring in Ruby?
The include? command sounds like what you should use.
my_string = "abcdefg"
if my_string.include? "cde"
puts "String includes 'cde'"
end
To be more accurate, #turno can contain a string like "ABC1" and res[:department] contains a string with "ABC" i need reduce the string in #turno to the first X characters and compare it with the content of res[:department]

Can I get the last value from an iterator?

I would like to split a string by a separator and get only the last part. I
don't care about the rest. I know I can do:
local last
for p in string.gmatch('file_name_test', '_%w+$') do last = p end
Which works, but is, IMHO, ugly.
Is there a more elegant way to say:
local last = string.gmatch('file_name_test', '_%w+$')[1]
Which doesn't work because gmatch returns an iterator (and not a table).
Use string.match which is not an iterator:
local last = string.match('file_name_test', '_(%w+)$')
print (last) --> test
Although the other answers do give you a correct answer for your situation, I am going to propose an answer to your question. Which was to get the first item from an iterator.
And the answer is actually quite simple. Since an iterator is just something that continues to return until it returns nil, we just have to call it!
local first = string.gmatch('file_name_test', '_%w+$')()
I am quite confused however, because in your question you also ask about the last thing it will return. I'm sad to say you cannot do this without iterating over them all, because an iterator cannot "jump ahead".
The pattern _%w+$ will only ever return a single match. That's because you anchored it at the end of the string, so it can only either match or fail to match (if there isn't an underscore followed by at least one %w character at the end).
The g* series of pattern matching are for iterating over a sequence of matches. If you want all the matches all at once (returned as multiple return values), use the non-g-prefixed functions. Like string.match:
string.match('file_name_test', '_%w+$')
If there is no match, then you'll get nil back.

Get line that matches regex in rails

I have a long list of information stored in a variable and I need to run some regex expressions against that variable and get various pieces of information from what is found.
How can you store the line that matches a regex expression in a variable?
How can you get the line number of the line that matches a regex expression?
Here is an example of what I'm talking about.
body = "service timestamps log datetime msec localtime show-timezone
service password-encryption
!
hostname switch01
!
boot-start-marker"
If I search for the line that contains "hostname" I need the line number, in this case it would be 4. I also need to store the line "hostname switch01" as another variable.
Any ideas?
Thanks!
First you'd want to convert the string to lines: body.split('\n'), then you want to add line numbers to the lines: .each_with_index. Then you want to select the lines .select {|line, line_nr| line =~ your_regex }. Putting it all together:
body.split('\n').each_with_index
.select {|line, line_nr| line =~ your_regex }
.map {|line, line_nr| line_nr }
This will give you all the lines matching 'your_regex'
Let's say you have an object file that provides a #lines method:
lines = file.lines.each_with_index.select {|line, i| line =~ /regex/ }
If you already have a list of lines you can leave out the call to #lines. If you have a string you can use string.split("\n").
This will result in the variable lines containing an array of 2-element arrays with the line that matched your RegEx and the index of the line in the original file.
Breakdown
file.lines gets the lines - of course the other methods I mentioned might also apply here for you. We then add the index to each element with #each_with_index, because you want to store these as well. This has the same effect as #map.with_index {|e, i| [e, i]}, i.e. map every element to [element, index]. We then use the #select method to get all lines that do match your RegEx (FYI, =~ is the matching operator in Ruby, Perl and other languages - in case you didn't already know). We're done after that, but you might need to further transform the data so you can process it.

How can I update parts of the string that matches some regexp

I have string "(1,2,3,4,5,6),(1,2,3)" I would like to change it to "('1','2','3','4','5','6'),('1','2','3')" - replase all parts that mathces /([^,)("])/ with the '$1', '$2' etc
"(1,2,3,4,5,6),(1,2,3)".gsub(/([^,)("]\w*)/,"'\\1'")
gsub is a "global replace" method in String class. It finds all occurrences of given regular expression and replaces them with the string given as the second parameter (as opposed to sub which replaces first occurrence only). That string can contain references to groups marked with () in the regexp. First group is \1, second is \2, and so on.
Try
mystring.gsub(/([\w.]+)/, '\'\1\'')
This will replace numbers (ints/floats) and words with their "quote-surrounded" selves while leaving punctuation (except the dot) alone.
UPDATED: I think you want to search for this
(([^,)("])+)
And replace it with this
'$1'
the looks for anything 1 or more times and assigns it to the $1 variable slot due to using the parenthesis around the "\d". The replace part will use what it finds as the replacement value.

Resources