Stacca
Stacca

Reputation: 831

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

Upvotes: 2

Views: 7713

Answers (2)

Ami Mahloof
Ami Mahloof

Reputation: 472

Use pry

gem install pry

its better than irb

everything in ruby is an object

dot notation on an object means that this is a method of that object

this is why you need to wrap it inside a class / module

I suggest read here for more info: https://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/45-more-classes/lessons/113-class-variables

Upvotes: 0

Beartech
Beartech

Reputation: 6411

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

Upvotes: 6

Related Questions