Domanda

In Ruby, a set can be initialized by Set[1,2,3] So can an array: Array[1,2,3]

Is it possible to write some code to do the same thing to my own classes? Or it's just a language feature for only a few built-in classes?

È stato utile?

Soluzione

In Ruby, foo[bar, baz] is just syntactic sugar for foo.[](bar, baz). All you need is a method named [].

By the way: you just need to look at the documentation, e.g. for Set:

[](*ary)

Creates a new set containing the given objects.

That's the documentation right there.

Basically, all you need is

class Foo
  def self.[](*args, &block)
    new(*args, &block)
  end
end

Altri suggerimenti

Yes, since [] and []= are just methods, they can be overridden.

You could try something like this:

class MyArray
  attr_accessor :data

  def self.[](*values)
    obj = MyArray.new
    obj.data = values
    return obj
  end
end
class X
  attr_accessor :contents

  def self.[](*x)
    obj = self.new
    obj.contents = x
    obj
  end
end
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top