How do I remove a substring after a certain character in a string using Ruby?
new_str = str.slice(0..(str.index('blah')))
Remove everything after some characters
This can be relatively easily accomplished by running split("More info")
on your strings. What that does is breaks the string in to an array like so:
new_string = "Posted today More info Go to Last Post"
new_string = new_string.split("More info")
# becomes ["Posted today ", " Go to Last Post"]
What split does is it breaks a string apart in to an array, where each element is what preceded the argument. So if you have "1,2,3"
then split(",")
will return [1, 2, 3]
So to continue your solution, you can get the posting date like this:
new_string[0].strip
.strip
removes spaces at the front or back of a string, so you'll be left with just "Posted today"
How to remove a certain character after substring in Ruby
If you don't want to use regex that sometimes difficult to understand use this:
def exclamation(sentence)
words = sentence.split
words_wo_exclams = words.map do |word|
word.split('').reverse.drop_while { |c| c == '!' }.reverse.join
end
words_wo_exclams.join(' ')
end
Remove substring from the string
You can use the slice method:
a = "foobar"
a.slice! "foo"
=> "foo"
a
=> "bar"
there is a non '!' version as well. More info can be seen in the documentation about other versions as well:
http://www.ruby-doc.org/core/classes/String.html#method-i-slice-21
Remove @ sign and everything after it in Ruby
To catch anything before the @ sign:
my_string = "user@example.com"
substring = my_string[/[^@]+/]
# => "user"
How to delete specific characters from a string in Ruby?
Do as below using String#tr
:
"((String1))".tr('()', '')
# => "String1"
How do I remove all characters in a string until a substring is matched, in Ruby?
or with the regex:
str = "Hey what's up @dude, @how's it going?"
str.gsub!(/.*?(?=@how)/im, "") #=> "@how's it going?"
you can read about lookaround at here
Related Topics
How to Specify a Required Switch (Not Argument) with Ruby Optionparser
Ruby: Character to Ascii from a String
Directory Layout for Pure Ruby Project
Parse CSV File with Header Fields as Attributes for Each Row
What's the Difference Between "Includes" and "Preload" in an Activerecord Query
Change the Context/Binding Inside a Block in Ruby
Hashes of Hashes Idiom in Ruby
Ruby on Rails: Devise, Want to Add Invite Code
Rspec: How to Test If a Method Was Called
Cannot Execute "Rails Console" Due to an Error with Readline
How to Handle Errors with Httparty
How to Use Dot Syntax for Ruby Hash
How to Create a Full Audit Log in Rails for Every Table
How to Loop Over a Hash of Hashes
Why Bundle Install Is Installing Gems in Vendor/Bundle
Undefined Instance Method "Respond_To" in Rails 5 API Controller