how to override [] brackets in ruby?

后端 未结 3 1812
灰色年华
灰色年华 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
    
    0 讨论(0)
  • 2020-12-17 20:59

    @German, tried to get answer for your question.

    2.1.3 :025 > class AntiArray < Array
    2.1.3 :026?>     def [](ind)
    2.1.3 :027?>         self.fetch(-ind) + 1
    2.1.3 :028?>     end
    2.1.3 :029?>   end
     => :[] 
    2.1.3 :030 > y = AntiArray.new([1,2,3,4])
     => [1, 2, 3, 4] 
    2.1.3 :031 > y[1]
     => 5 
    2.1.3 :032 > 
    

    Hope this is what you are asking for. Given a try for you

    0 讨论(0)
  • 2020-12-17 21:02

    You need to use params[:Jobs][:clearance]

    params is a hash of all the request parameters. But params[:Jobs] is ALSO a hash of all :Jobs parameters. So calling params[:Jobs][:clearance] is calling the [] method on the params[:Jobs] object passing :clearance in as a parameter.

    0 讨论(0)
提交回复
热议问题