I was looking for awhile on here and didn't quite find what I needed. I am learning Ruby(1.9) and am trying to do something basic with a text file. I am trying to use RegEx's to remove non-letters, and white space that is ONLY at the beginning of the line, ignoring spaces between tokens(I am trying to count words in the file, hence when I want the spaces between words to remain).
Ex:
555 r6ub6y i7s e7a0sy... w1o2w4.
To change to:
ruby is easy... wow.
What I have so far using the command-line to test ruby rubyfile.rb < test.txt
:
$stdin.each do |line|
line.chomp!.downcase!
line.gsub!(/[^a-zA-Z]/, "") #this takes away my spaces!
puts line
end
How to remove certain characters from a string Ruby? In Ruby, we can permanently delete characters from a string by using the string. delete method. It returns a new string with the specified characters removed.
=~ 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.
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