Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby gsub : is there a better way

Tags:

ruby

I need to remove all leading and trailing non-numeric characters. This is what I came up with. Is there a better implementation.

puts s.gsub(/^\D+/,'').gsub(/\D+$/,'')
like image 664
Roger Avatar asked Dec 29 '22 07:12

Roger


1 Answers

Instead of eliminating what you don't want, it's often clearer to select what you do want (using parentheses). Also, this only requires one regex evaluation:

s.match(/^\D*(.*?)\D*$/)[1]

Or, this convenient shorthand:

s[/^\D*(.*?)\D*$/, 1]
like image 112
Alex Reisner Avatar answered Jan 11 '23 08:01

Alex Reisner