Ivan Kutsarov
Ivan Kutsarov

Reputation: 1031

Ruby method help required

I am reading Metaprogramming Ruby book, and there is method, which I cant understant:

def to_alphanumeric(s)
  s.gsub /[^\w\s]/, ''
end

I see there is Argument Variable (s), which is called lately and is converted to some weird expression? What exactly can I do with this method, is he useful?

Following method works just fine:

def to_alphanumeric(s)
  s.gsub %r([aeiou]), '<\1>'
end

p = to_alphanumeric("hello")
p p
>> "h<>ll<>"

But if I upgrade method to class, simply calling the method + argv to_alphanumeric, no longer work:

class String 
  def to_alphanumeric(s)
    s.gsub %r([aeiou]), '<\1>'
  end
end
p = to_alphanumeric("hello")
p p
undefined method `to_alphanumeric' for String:Class (NoMethodError)

Upvotes: 0

Views: 80

Answers (2)

0x4a6f4672
0x4a6f4672

Reputation: 28245

Take a look at Rubular, the regular expression /[^\w\s]/ matches special characters like ^, /, or $ which are neither word characters (\w) or whitespace (\s). Therefore the function removes special characters like ^, / or $.

>> "^/$%hel1241lo".gsub /[^\w\s]/, ''
=> "hel1241lo"

call it simple like a function:

>> to_alphanumeric("U.S.A!")
=> "USA"

Upvotes: 1

erdeszt
erdeszt

Reputation: 791

Would it hurt to check the documentation?

http://www.ruby-doc.org/core-2.0/String.html#method-i-gsub

Returns a copy of str with the all occurrences of pattern substituted for the second argument.

The /[^\w\s]/ pattern means "everything that is not a word or whitespace"

Upvotes: 1

Related Questions