Ruby,如何控制调用实例化对象的返回值

标签 ruby

如果我这样做:

class PseudoRelationship
    def my_method(args)
         args
    end
end

a = PseudoRelationship.new

我得到了输出

x
#<PseudoRelationship:0x109c2ebb0>

我希望它表现得像一个枚举器或数组,所以我得到了例如这个输出

x = PseudoRelationship.new [1,2,3]
x
[1,2,3]

钯。这不适用于 Rails。

我想做的是表现得像一个数组。

rails 2.3好像用的东西,比如你可以做

my_model.relationship # returns an array
my_model.relationship.find #is a method

我正在尝试复制该行为。

最佳答案

jholtrop 很接近,你想覆盖 inspect 方法

2.0.0p645> 
class PseudoRelationship
    def initialize(args)
        @args = args
    end

    def inspect
        @args.inspect
    end
end

2.0.0p645> PseudoRelationship.new [2, 3, 5]                                                                                                                                                                 
[2, 3, 5]

--根据 OP 的想要这种行为的原因进行编辑--

虽然上面的类在控制台中显示我们想看到的,但它实际上并没有以将 args 视为 Enumerable 的方式假设对 args 进行任何管理. OP 的灵感来自 Rails 构造,ActiveRecord::Relation*。要模拟这种行为风格,您必须包含 Enumerable。

class PseudoRelationship
    include Enumerable

    def initialize(args)
        @args = args
    end

    def each(&block)
       @args.each(&block)
    end

    def inspect
        @args.inspect
    end

    # Add extra functions to operate on @args
    # This is obviously a silly example
    def foo?
      @args.include? :foo
    end

    def [](key)
      @args[key]
    end

    def last
      @args[-1]
    end
end


2.0.0p645> PseudoRelationship.new [2, 3, 5]                                                                                                                                                                 
[2, 3, 5]
2.0.0p645> x = PseudoRelationship.new [2, 3, 5]
[2, 3, 5]
2.0.0p645> x.each 
#<Enumerator: [2, 3, 5]:each>
2.0.0p645> x.each_with_index
#<Enumerator: [2, 3, 5]:each_with_index>
2.0.0p645> x.each_with_index { |e, i| puts "#{i} => #{e}" }
0 => 2
1 => 3
2 => 5
[2, 3, 5]
2.0.0p645> x.foo?
false
2.0.0p645> x.first
2
2.0.0p645> x.last
5
2.0.0p645> x[1]
3
2.0.0p645> x[5]
nil
2.0.0p645> x
[2, 3, 5]

* 这个构造没有明确说明,但我是根据上下文假设的

关于Ruby,如何控制调用实例化对象的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33268694/

相关文章:

python - 我可以在 C 中使用 Python/Ruby ORM 吗?

ruby-on-rails - 使用 AASM 的 ActiveRecord 模型上的 delayed_job - 吞下失败的方法错误,而是抛出 "wrong number of arguments"

ruby - 这两种使用 put 命令的方法有什么区别?

ruby - 帮助一个简单的方法

ruby-on-rails - 一个存储文件的地方(Ruby on Rails)

ruby - 如何在案例中使用 "break"...而在 Ruby 中

javascript - 使用 JavaScript 在 Rails 应用程序的一个 View 中渲染一系列 Google map

ruby - Rails 3.2.11 应用程序中的 Assets 管道在 Ruby 1.9.3 中工作正常,但在 Ruby 2.0.0 中停止工作

ruby-on-rails - 验证 Facebook + Twitter + Instagram 的访问 token

ruby-on-rails - 将带时区的日期时间字符串转换为带时区的日期时间或 rails 3 中的 UTC