简体   繁体   中英

Rails/Ruby Over ride to_s for array object

In my rails form i am using a multi select tag

code looks like

  <%= select_tag '[mycontroller][users]', @users, { :multiple => true, :size => 7} %>
  <p><%= submit_tag l(:button_apply)%></p>

On form submit parameters passed are

 mycontroller[users][]=79&mycontroller[users][]=80&commit=Apply

Now in my view file when i retrieve params they are being converted to string so i get [79,80] being converted to "7980"

code for getting user param looks like

users =  params[:mycontroller][:users] unless params[:mycontroller].nil? 

Edit :

Problem i suppose is that "#{}" converts array to string. even <%= %> will call to_s

So how to override this? So that to_s will return "79,80" instead of "7980"

What am i missing? Comments, please?

Thnx.

Overriding to_s seems very heavy handed.

You can either iterate through the array displaying each element individually (usually more readable if you're presenting something complicated for each element, or use something like my_array.join(',') if you just want to comma separate the array elements.

Try to call array.join(",") and a array of [79,80] should become a string like "79,89"

Ruby Join Method

I dint know that Array.join returns string, so i was trying to solve it in my own way. This may not be efficient/effective but its a workaround.

arr = [79,80]
a =arr.inject(0){|op,i| op.to_s + i.to_s + ","}.to_s  
a[1,a.length-2] # "79,80"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM