Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading array of params in RoR

If I have URL something like below:

http://test.com?x=1&x=2&x=3&x=4&x=5&x=6&x=7

Then how can I read all "x" values?

Added new comment: Thanks for all your answers. I am basically from Java and .Net background and recently started looking Ruby and Rails. Like in Java, don't we have something similar as request.getParameterValues("x");

like image 617
Sudhakar Chavali Avatar asked Apr 13 '11 10:04

Sudhakar Chavali


2 Answers

You should use following url instead of yours:

http://test.com?x[]=1&x[]=2

and then you'll get these params as array:

p params[:x] # => ["1", "2"]
like image 180
Vasiliy Ermolovich Avatar answered Oct 14 '22 14:10

Vasiliy Ermolovich


IF IT IS A STRING, but not a http request

Do this:

url = 'http://test.com?x=1&x=2&x=3&x=4&x=5&x=6&x=7'

p url.split(/(?:\A.*?|&)x=/).drop(1)

If you want to convert them to integers, do:

p url.split(/(?:\A.*?|&)x=/).drop(1).map(&:to_i)  (ruby 1.9)

or

p url.split(/(?:\A.*?|&)x=/).drop(1).map{|v| v.to_i}
like image 26
sawa Avatar answered Oct 14 '22 14:10

sawa