ruby 类别问题
PHP中文网
PHP中文网 2017-04-22 08:59:38
0
2
693

class 的问题 (不好意思,我的理解能力很差)

  1. instance method, variable
  2. class method, variable

我已经阅读其他ruby书籍,还是不懂它区别在哪。
一样是方法和变量,这2个的差别或用意在那里?

还有最后一个问题是self
self是什么?

希望各位大大,能帮我解决这些问题,希望能举几个简单简明的例子^^
谢谢^^

PHP中文网
PHP中文网

认证0级讲师

reply all(2)
洪涛

I'll try to post a code to explain it. If you don't understand, please ask me in the comments.

#!/usr/bin/env ruby
# encoding: UTF-8

class Trivia
  @@x = 10

  def instance_scope_x
    @x
  end

  def instance_scope_x=(x)
    @x = x
  end

  def self.class_scope_x
    @@x
  end

  def self.class_scope_x=(x)
    @@x = x
  end
end

a = Trivia.new
# 只有Trivia对象才能使用class方法。所以这里用a.class返回Trivia对象
p "The class scope x in a : #{a.class.class_scope_x}"
a.instance_scope_x = 20
p "The instance scope x in a : #{a.instance_scope_x}"

b = Trivia.new
# Trivia的实例修改自身的值,不会影响同个类的其他实例
p "The instance scope x in b : #{b.instance_scope_x}"
p "The class scope x in b : #{b.class.class_scope_x}"
b.class.class_scope_x = 30
# 修改了Trivia类的值。因为a和b共享同一个类对象(都指向Trivia),所以现在值改变了
p "Now the class scope x in a : #{a.class.class_scope_x}"

# self指向当前作用域的所有者
class Trivia
  # 类作用域
  p self

  def self_scope_x
    # 实例作用域
    p self
    # 这里self指向实例作用域
    self.instance_scope_x
  end

  def self.self_scope_x
    # 这里self指向类作用域
    self.class_scope_x
  end
end

p "The self_scope_x in Trivia: #{Trivia.self_scope_x}" # 调用的是class_scope_x
p "The self_scope_x in Trivia's instance: #{a.self_scope_x}" # 调用的是instance_scope_x
阿神

I will explain these issues in the article, welcome to pay attention

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template