RubyFlow The Ruby and Rails community linklog


The Ruby and Rails community linklog

Made a library? Written a blog post? Found a useful tutorial? Share it with the Ruby community here or just enjoy what everyone else has found!

Clamp strings, symbols, array or hashes

The clamped gem allows to filter values by a provided whitelist. For example, "apple".clamped(%w[apple banana]) # "apple". If apple is not part of the array, nil is returned. This is e.g. useful to filter values provided by user input.

Ruby already supports clamping numbers:

10.clamp(12, 20) # 12

The clamped gem extends this to strings, symbols, arrays and hashes.

For example:

"apple".clamped(%w[banana orange]) # nil

"apple".clamped(%w[apple banana]) # "apple"

This is mostly useful when whitelisting user input:

ROLES = ["admin", "user"]

# assume params[:role] == "superadmin"

params[:role].clamped(ROLES, default: "guest") # "guest"

Install with gem install clamped or put gem "clamped" in your Gemfile. More information on

Post a comment

You can use basic HTML markup (e.g. <a>) or Markdown.

As you are not logged in, you will be
directed via GitHub to signup or sign in