【问题标题】:Ruby Get Caller Object's Name Inside Method Using Default LibraryRuby使用默认库在方法内部获取调用者对象的名称
【发布时间】:2014-02-02 07:36:11
【问题描述】:

我有以下问题。我想要一个方法,我们称它为method_A,检查调用method_A的对象名称。

这是一个简单的参考,但我要做的事情会比这复杂得多,我知道有一种替代方法可以以更好的方式解决我需要的问题,但是可惜代码几乎完成了,并且我没有足够的时间来调整很多。不管怎样,就这样吧:

class Picture
  attr_accessor :size

  def resize
    name = self.get_object_name_here
    case name
    when Big #Can be string or variable, I don't mind
      self.size *= .5
    when Medium
    when Small
      self.size *= 2
    else
    end

  def get_object_name_here
    object_name
  end
end

Big = Picture.new
Medium = Picture.new
Small = Picture.new
Big.size = 10
Medium.size = 10
Small.size = 10
Big.resize       => 5
Medium.resize    => 10
Small.resize     => 20

如果有办法做到这一点

name = object_name

那会很有帮助

非常感谢!

编辑:对于大写的 Big、Medium、Small 感到抱歉。他们是错别字。

【问题讨论】:

  • object_name 是什么意思?在你的例子中他们会是Big, Medium and Small吗?
  • 是的,是的,它们将是 Big、Medium 和 Small。
  • 我认为这不可能实现,因为这些是已分配给 Picture 对象的变量的名称:Picture 不可能知道哪个您正在使用的变量。
  • 好吧,任何识别哪个对象(不是类)正在调用此方法的方法都会非常有帮助。我只需要案例操作员来工作。
  • 那么你将不得不改变类来为 name 属性添加一个 setter,就像你为 size 所做的那样。

标签: ruby object methods


【解决方案1】:

你必须改变你的类的定义

class Picture
  attr_accessor :size, :name

  def initialize(name)
    @name = name
    @size = 10
  end

  def resize
    case name
    when "Big"
      self.size *= 0.5
    when "Medium"
    when "Small"
      self.size *= 2
    else
    end
  end
end

当您使用new 传递所有参数时,Ruby 将调用initialize 方法。你可以像这样使用这个类:

big = Picture.new("Big")
medium = Picture.new("Medium")
small = Picture.new("Small")

puts "before resize"

puts big.size
puts medium.size
puts small.size

big.resize
medium.resize
small.resize

puts "after resize"

puts big.size
puts medium.size
puts small.size

结果

before resize
10
10
10
after resize
5.0
10
20

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多