reading array of params in RoR
If I have URL something like b开发者_如何学Celow:
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");
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"]
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}
IF IT IS A STRING, but not a http request I even didn't imagine if author don't know how to handle params of request url...
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 need to extract valuse only:
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]
精彩评论