Just started with Ruby, and got stuck up with inline edit constructs:
v1="SO"
print v1.gsub!(/\W/,"").reverse
v2="SO!!"
print v2.gsub!(/\W/,"").reverse
v1.gsub! results in nil. Why? v2.gsub! works.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The key here is that you’re using the mutating version of
gsub,gsub!, which modifies the actual string it is called on. As for what it returns, the documentation says it best:You should either use the non-mutating version,
gsub, if you don’t actually wish to modify the string it is called on:Or you can do the substitution before printing the variable:
Or, in Ruby 1.9, you can use
tap: