Search code examples
rubyirb

Defining and calling a method in irb


I'm struggling with understanding understanding OOP. I am trying to use IRB to play around with Ruby and deepen my understanding.

In IRB

foo = Object.new

Creates a new object However if I try and give irb a definition and call it on that object it doesn't work. (does the def have to happen in a .rb file and loaded into Ruby?)

def bar "hello" end

Solution

  • You need to define the method in the class you want it to apply to.

    class NewObject
      def foo
        puts "hello"
      end
    end
    

    these methods are called like:

    x = NewObject.new
    x.foo
    

    You can create methods that are not specific to a class just by defining them:

     def bar
       puts "bar!"
     end
    

    and just call them as:

    bar