Reading an array of parameters in RoR

If I have a url like:

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

Then how can I read all the values ​​of "x"?

New comment added: Thanks for all your answers. I am mainly from Java and .Net background and recently started looking for Ruby and Rails. Like in Java, don't we have something like request.getParameterValues ​​("x");

+6
source share
3 answers

If it is STRING but not an http request

Do it:

 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} 
+3
source

You should use the following url instead of yours:

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

and you will get these parameters as an array:

 p params[:x] # => ["1", "2"] 
+26
source

If this is STRING, but not an http request , I did not even imagine if the author might not know how to handle the request url parameters ...

 url = "http://test.com?x=1&x=2&x=3&x=4&x=5&x=6&x=7" vars = url.scan(/[^?](x)=([^&]*)/) #=> [["x", "2"], ["x", "3"], ["x", "4"], ["x", "5"], ["x", "6"], ["x", "7"]] x = vars.map{|a| a[1]} #=> ["2", "3", "4", "5", "6", "7"] x.map!(&:to_i) #=> [2, 3, 4, 5, 6, 7] 

Or, if you only need to remove the valuza:

 vars = url.scan(/[^?]x=([^&]*)/).flatten #=> ["2", "3", "4", "5", "6", "7"] vars = url.scan(/[^?]x=([^&]*)/).flatten.map(&:to_i) #=> [2, 3, 4, 5, 6, 7] 
+2
source

Source: https://habr.com/ru/post/885806/


All Articles