“this"的 Ruby 等价物是什么?Java中的函数? [英] What is the Ruby equivalent of the "this" function in Java?

查看:53
本文介绍了“this"的 Ruby 等价物是什么?Java中的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中有一个指向它的方法的this"函数.Ruby 中是否有等价物?例如,是否有:

In Java there is a "this" function that points to its method. Is there an equivalent in Ruby? For instance, is there:

def method
  this.method
end

推荐答案

相当于 self.这也是隐含的.所以self.first_name 和班级中的first_name 是一样的,除非你是在做作业.

The equivalent is self. It is also implict. So self.first_name is the same as first_name within the class unless you are making an assignment.

class Book
  attr_reader :first_name, :last_name

  def full_name
     # this is the same as self.first_name + ", " + self.last_name
    first_name + ", " + last_name
  end
end

在进行赋值时,您需要显式使用 self,因为 Ruby 无法知道您是在分配名为 first_name 的局部变量还是分配给 instance.first_name.

When making an assignment you need to use self explicitly since Ruby has no way of knowing if you are assigning a local variable called first_name or assigning to instance.first_name.

class Book    
  def foo
    self.first_name = "Bar"
  end
end

这篇关于“this"的 Ruby 等价物是什么?Java中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆