I am a new ruby user and I want to add a function to an existing class.
I googled the answer and found part of the solution. All findings on the
web adding a new method without a variable. In my case I want to use the
string as a variable. Here is what I want to do:
class String
def convert(x) #code to convert the x
x.upcase
end
end
What I want is in the irb I can use the new method in the way as:
“a”.convert
This will convert a to upper case. However, it does not take the “a” as
the input variable and generating error
ArgumentError: wrong number of arguments (0 for 1)
–Marcin’s way is perfect; but there is something we don’t understand
about your requirement:
"…I want to use the string as a variable
def convert(x)
#code to convert the x
…"
then…"in the irb I can use the new method in the way as:
“a”.convert <—what’s happened to ur variable x???
Best Regards,
frank hi wrote in post #1019491:
Hi,
I am a new ruby user and I want to add a function to an existing class.
I googled the answer and found part of the solution. All findings on the
web adding a new method without a variable. In my case I want to use the
string as a variable. Here is what I want to do:
class String
def convert(x) #code to convert the x
x.upcase
end
end
What I want is in the irb I can use the new method in the way as:
“a”.convert
This will convert a to upper case. However, it does not take the “a” as
the input variable and generating error
ArgumentError: wrong number of arguments (0 for 1)
Basically, I wrote my own method and want to add to the existing class
and expected that the “string”.convert will pass the “string” to the
method. However, I could not find the solution to let the convert method
takes the “string” as input. the self pointer solved the issue.
Thanks
Frank
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.