问题
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
回答1:
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
回答2:
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
来源:https://stackoverflow.com/questions/29361503/defining-and-calling-a-method-in-irb