开发者

Ruby .gsub how to shorten a line of code that makes similar substitutions

开发者 https://www.devze.com 2023-02-11 21:09 出处:网络
I have a line of Ruby code that looks something like this: words = params[:words].gsub(\"\\n\",\"\").gsub(\"\\s\",\"\")

I have a line of Ruby code that looks something like this:

words = params[:words].gsub("\n","").gsub("\s","")

Is there a better way to do this since the code takes all spaces and newlines and gets rid of them? Just curious if there is a better or shorter way, in the case that I'm being too repetitive in my code.

The above code does work for me, but I'm new to programming and want to do things the better/more aesthetic way if p开发者_如何学Cossible.


actually, using only \s to match any whitespace character should work:

"some\n simple  demo \nstring \n".gsub(/\s/, "")  # => "somesimpledemostring"


words = params[:words].delete("\s\n")
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号