Defining and calling a method in irb

馋奶兔 提交于 2019-12-24 13:41:05

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!