Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

how to override [] brackets in ruby?

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

<%= collection_select("Jobs", "clearance", @allClearances, "clearance", "clearance", {:prompt => "Select a Clearance"} )%>

Ruby then builds an HTML select tag with id = "Jobs_clearance" and name = "Jobs[clearance]"

I want to send the parameter to my controller, which looks like this:

class JobsController < ApplicationController
  def foo
    @clearance = params[:Jobs[clearance]]
  end

Unfortunately, Ruby only reads ":Jobs" as the symbol instead of ":Jobs[clearance]"
Is there a way to escape the []'s? backslash isn't working.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...