Today I Learned

hashrocket A Hashrocket project

Convert objects into URL query strings

In Rails you can easily convert objects into URL query strings.

Here are a few examples:

string = "vanilla"
big_string = "extra chocolate"
integer = 5
array = ["vanilla", "chocolate"]
hash = {flavor: "vanilla", scoops: 2}

string.to_query("flavor")
=> "flavor=vanilla"

big_string.to_query("flavor")
=> "flavor=extra+chocolate"

integer.to_query("scoops")
=> "scoops=5"

array.to_query("flavors")
=> "flavors%5B%5D=vanilla&flavors%5B%5D=chocolate"

hash.to_query
=> "flavor=vanilla&scoops=2"

Note: Hashes don't require a key to be passed in, because they are inferred from the hash keys.

See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.