开发者

Ruby - Calling a method from a child object

I'm new to Ruby and trying to determine how I can call a class from a child object. Something like the below; however when I try it, I get an error saying "undefined local variable or method `me'"

class my_object < Object
    attr_acces开发者_如何学Gosor :me

    def initialize(attributes ={})
    end


    def setvalue(passed_value)
      @passed_value = passed_value.to_s
    end 

    def search(passed_value) 
      @passed_value.include?(passed_value)
    end

   end

   def getMe
    me_too = my_object.new
    me_too.me = "test"
    me_too.me.search("test")

   end
end


instance.class

will give you a reference to the class


This works: But your code had multiple errors.

class MY
    attr_accessor :me

    def initialize(attributes ={})
    end


    def setvalue(passed_value)
      passed_value = passed_value.to_s
    end

    def search(passed_value)
      passed_value.include?(passed_value)
    end


   def getMe
    me_too = MY.new
    me_too.me = "test"
    me_too.search("test")

   end
end

my = MY.new
my.getMe


  • You don't need to explicity extend Object, everything extends Object in ruby.
  • Your class name needs to start with a capital letter.

    class MyObject attr_accessor :me

    end

    me_too = MyObject.new me_too.me = "test"

in console

me_too => #<MyObject:0x106b2e420 @me="test"> 

Check out some introductory ruby tutorials maybe http://ruby.learncodethehardway.org/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜