Ruby language function for Set [1,2,3]

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

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

+4
source share
3 answers

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

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

[](*ary)

Creates a new set containing these objects.

What is the documentation there.

Basically, all you need is

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

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

You can try something like this:

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

All Articles