how to override [] brackets in ruby?

后端 未结 3 1818
灰色年华
灰色年华 2020-12-17 20:19

I am writing an Ajax request form with Ruby on Rails using a collection_select tag that looks like this:

<%= collection_select(\"Jobs\", \"cl         


        
3条回答
  •  既然无缘
    2020-12-17 20:42

    kmorris solved your problem (very well) but i would like to answer your question: you can override [] and []= operators because they are methods (like almost everything), but you should think well about what you are doing because you can break tons of things.

    class AntiArray < Array
    
      def [](ind)
        self.fetch(-ind)
      end
    
    end
    
    y = AntiArray.new([1,2,3,4])
    
    y[1]
    
    => 4
    

提交回复
热议问题