mirror of
https://github.com/jbranchaud/til
synced 2026-01-04 23:58:01 +00:00
Add Parameterize A String With Underscores as a Rails TIL
This commit is contained in:
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
|
||||
|
||||
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
|
||||
|
||||
_1654 TILs and counting..._
|
||||
_1655 TILs and counting..._
|
||||
|
||||
See some of the other learning resources I work on:
|
||||
- [Get Started with Vimium](https://egghead.io/courses/get-started-with-vimium~3t5f7)
|
||||
@@ -1093,6 +1093,7 @@ If you've learned something here, support my efforts writing daily TILs by
|
||||
- [Mock Rails Environment With An Inquiry Instance](rails/mock-rails-environment-with-an-inquiry-instance.md)
|
||||
- [Order Matters For `rescue_from` Blocks](rails/order-matters-for-rescue-from-blocks.md)
|
||||
- [Override Text Displayed By Form Label](rails/override-text-displayed-by-form-label.md)
|
||||
- [Parameterize A String With Underscores](rails/parameterize-a-string-with-underscores.md)
|
||||
- [Params Includes Submission Button Info](rails/params-includes-submission-button-info.md)
|
||||
- [Params Is A Hash With Indifferent Access](rails/params-is-a-hash-with-indifferent-access.md)
|
||||
- [Parse Query Params From A URL](rails/parse-query-params-from-a-url.md)
|
||||
|
||||
40
rails/parameterize-a-string-with-underscores.md
Normal file
40
rails/parameterize-a-string-with-underscores.md
Normal file
@@ -0,0 +1,40 @@
|
||||
# Parameterize A String With Underscores
|
||||
|
||||
I have human-readable status strings that I'm working with like `In progress`,
|
||||
`Pending approval`, and `Completed`. I need to deterministically turn those
|
||||
into parameterized values that I can compare. That is, I want them lowercased
|
||||
and separated by underscores instead of spaces.
|
||||
|
||||
The `ActiveSupport` `#parameterize` method, as is, gets me pretty close.
|
||||
|
||||
```ruby
|
||||
> statuses = [
|
||||
"In progress",
|
||||
"Pending approval",
|
||||
"Completed"
|
||||
]
|
||||
|
||||
> statuses.map(&:parameterize)
|
||||
=> [
|
||||
"in-progress",
|
||||
"pending-approval",
|
||||
"completed"
|
||||
]
|
||||
```
|
||||
|
||||
Those are separated by dashes though. Fortunately, `parameterize` takes a
|
||||
`separator` option that we can use to verride what character is used to
|
||||
separate words. Let's use an underscore (`_`).
|
||||
|
||||
```ruby
|
||||
> statuses.map { |str| str.parameterize(separator: '_') }
|
||||
=> [
|
||||
"in_progress",
|
||||
"pending_approval",
|
||||
"completed"
|
||||
]
|
||||
```
|
||||
|
||||
See the [`#paramterize`
|
||||
docs](https://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-parameterize)
|
||||
for more details.
|
||||
Reference in New Issue
Block a user