Parse comma separated values
I would like to parse comma separated values from a url parameter in Ruby on Rails.
For example how to parse the following?
http:开发者_StackOverflow中文版//example.com/?fields=1,2,3
I would like to be able to use params[:fields] in my controller. Is that creating an array? Should I use for loop?
foo = params[:fields].split(',')
> a = "1,2,3"
=> "1,2,3"
> a.split(',')
=> ["1", "2", "3"]
> a.split(',').each {|element| p element}
"1"
"2"
"3"
=> ["1", "2", "3"]
> a.split(',').map(&:to_i)
=> [1, 2, 3]
foo = params[:fields].split(',').map { |i| Integer(i) }
This will convert the fields params to integers and will validate your fields params if you want them to be integers.An Argument error will raise if that's not the case.(ex. http://example.com/?fields=1,2,test)
精彩评论