Different ways of calling methods?


#1

Hello I'm having difficulty invoking a bit of code

string = "this is a string"

def capy(string)
first= string(0)
rest = string(1..-1)
first.upcase + rest
end

string.capy

Am i not invoking this correctly or is the capy method wrong? I've tried some other things too that wont work..

Would you mind elaborating a few different ways to invoke the code???


#2

error code "undefined method `string' for main:Object (NoMethodError)"


#3

To invoke a function that has a parameter, we woutd write:

my_function(argument)

capy(string)

It would help if we had some context to go with this question. Can you post a link, please? Thanks.


#4

If you want to invoke it as string.capy, you have to monkeypatch the String class, i.e. define capy within class String. However, String already has a method which does exactly this (it is called capitalize), so there is no reason why you want your own capy method.


#5

There is no harm is trying to do things without using built-in methods. It's the best way to learn and practice the basics of logic and mechanics. When we know how to do something that a built-in method does, it gives us a greater appreciation of the method in real world work flow.


#6

Thanks for the replys both are helpful.

Im trying to get the gist of makking helper methods.... but having difficulty .

Do you know where theres good documentation for proper nesting practices and where & when to employ helper methods?

thanks again


#7

That will require defining a class. For simplicity, and only as a pseudo-code example,

class Strings
    def initialize(value)
        @string_value = value
    end

    def capy
        this = @string_value
        # do capitalization on 'this'
    end
end

my_string = Strings.new("Hello World!")

my_string.capy

For more detailed reading on writing classes, I found this page...

Writing our own classes

I found this somewhat related but advanced article...

Ruby: Extending Classes and Method Chaining


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.