As noted by @Mark Thomas, the functionality you are specifically looking for is already a part of the language, by using:
"this string, has, alot, of, commas,,,".delete ","
but if you are looking to add new functionality anyway, there are a few ways to do it.
Looking at your desired code:
string = "this string, has, alot, of, commas,,,"
string.delete_commas # => "this string has alot of commas"
You have to look at what object is receiving the message you're sending. In this case the "this string, has, alot, of, commas,,,"
object, which is an instance of String
. In order for that object to respond to that message, the String
class needs to implement a method of that name, as @shivam suggests.
It is important to note that this is what is affectionately referred to as a monkey patch. This comes with some drawbacks, some of which are listed in the article I linked.
A safer way of attaining this goal as of Ruby 2.0 is Refinements. By declaring a module that defines the refinement to the string class, you can choose exactly the scope at which you want to refine strings:
module ExtraStringUtils
refine String do
def delete_commas
gsub(',','')
end
end
end
class MyApplication
using ExtraStringUtils
"this string, has, alot, of, commas,,,".delete_commas
#=> this string has alot of commas
end
"this string, has, alot, of, commas,,,".delete_commas
#=> NoMethodError: undefined method `delete_commas' for "this string, has, alot, of, commas,,,":String
In other words, you have access to your special changes to String
wherever you are using ExtraStringUtils
, but nowhere else.
One last way to have a similar outcome is to have your own class that implements that method and operates on a string internally:
class MySuperSpecialString
def initialize string
@string = string
end
def delete_commas
@string.gsub!(',','') #gsub! because we want it to permenantly change the stored string
end
end
At which point the usage would be:
string = MySuperSpecialString.new("this string, has, alot, of, commas,,,")
string.delete_commas # => "this string has alot of commas"
This approach comes with its own special set of drawbacks, the biggest of which being that it does not respond to all the methods a string would. You can use delegation to pass unknown methods to the string, but there are still some seams where it won't behave exactly like a string and it won't behave exactly as a separate class, so be aware of the return values.