我正在努力理解理解 OOP。我正在尝试使用 IRB 来玩 Ruby 并加深我的理解。
在 IRB
foo = Object.new
Run Code Online (Sandbox Code Playgroud)
创建一个新对象 但是,如果我尝试给 irb 一个定义并在该对象上调用它,则它不起作用。(def 是否必须发生在 .rb 文件中并加载到 Ruby 中?)
def bar "hello" end
Run Code Online (Sandbox Code Playgroud)
您需要在要应用的类中定义方法。
class NewObject
def foo
puts "hello"
end
end
Run Code Online (Sandbox Code Playgroud)
这些方法被称为:
x = NewObject.new
x.foo
Run Code Online (Sandbox Code Playgroud)
您可以通过定义它们来创建不特定于类的方法:
def bar
puts "bar!"
end
Run Code Online (Sandbox Code Playgroud)
并将它们称为:
bar
Run Code Online (Sandbox Code Playgroud)