简体   繁体   中英

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://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 )

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