Ruby 中的 Setter 方法别名

发布于 2024-10-19 10:19:52 字数 767 浏览 4 评论 0原文

Ruby 中的别名方法相对简单。一个人为的示例:

class Person
  def name
    puts "Roger"
  end
end

class User < Person
  alias :old_name :name
  def name
    old_name
    puts "Staubach"
  end
end

在这种情况下,运行 User.new.name 将输出:

Roger
Staubach

That Works as expected。但是,我正在尝试为 setter 方法添加别名,这显然并不简单:

class Person
  def name=(whatever)
    puts whatever
  end
end

class User < Person
  alias :old_name= :name=
  def name=(whatever)
    puts whatever
    old_name = whatever
  end
end

这样,调用 User.new.name = "Roger" 将输出:

Roger

看来新的别名方法被调用,但原始版本没有。

这是怎么回事?

ps - 我知道 super ,为了简洁起见,我不想在这里使用它

Aliasing methods in Ruby is relatively straight-forward. A contrived example:

class Person
  def name
    puts "Roger"
  end
end

class User < Person
  alias :old_name :name
  def name
    old_name
    puts "Staubach"
  end
end

In this case, running User.new.name will output:

Roger
Staubach

That works as expected. However, I'm trying to alias a setter method, which is apparently not straight-forward:

class Person
  def name=(whatever)
    puts whatever
  end
end

class User < Person
  alias :old_name= :name=
  def name=(whatever)
    puts whatever
    old_name = whatever
  end
end

With this, calling User.new.name = "Roger" will output:

Roger

It appears that the new aliased method gets called, but the original does not.

What is up with that?

ps - I know about super and let's just say for the sake of brevity that I do not want to use it here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

鸠魁 2024-10-26 10:19:52

我认为当 Ruby 缺少对象引用时,它不会将 old_name =whatever 识别为方法调用。尝试:

def name=(whatever)
  puts whatever
  self.old_name = whatever
end

改为(注意 self.

I don't think Ruby will recognize old_name = whatever as a method call when it lacks an object reference. Try:

def name=(whatever)
  puts whatever
  self.old_name = whatever
end

instead (note the self.)

此岸叶落 2024-10-26 10:19:52

试试这个:

alias old_name= name=

Try this:

alias old_name= name=
百善笑为先 2024-10-26 10:19:52

你需要self.old_name =whatever,只是简单的old_name是本地的。

You need self.old_name = whatever, just plain old_name is a local.

分分钟 2024-10-26 10:19:52

别名是否必须是 setter?

class User < Person
  alias :old_name :name=
  def name=(whatever)
    old_name whatever
  end
end

Does the alias have to be a setter?

class User < Person
  alias :old_name :name=
  def name=(whatever)
    old_name whatever
  end
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文