Ruby: how to dasherize un String without using ActiveSupport

Viewed 135

As the title says, I'd like to dasherize a String by chunks of 3 characters, e.g.:

str = '123456789'
str.dasherize => # '123-456-789'

It should be done outside Rails ActiveSupport or any other gems.

3 Answers

You could do:

'123456789'.scan(/.{1,3}/).join('-')
  #=> "123-456-789"
'1234567890'.scan(/.{1,3}/).join('-')
  #=> "123-456-789-0"
'12345678901'.scan(/.{1,3}/).join('-')
  #=> "123-456-789-01"

This is splitting the string into an Array of 1-3 character chunks, then re-joining them with a hyphen.

You didn't specify how such a method should behave if the string's length is not a multiple of 3, but you could tweak the above approach to get some other result if desired.

One liner:

"123456789".chars.each_slice(3).map(&:join).join('-')

Explanation:

"123456789"
  .chars         # returns an Enumerator that yields each character
  .each_slice(3) # groups the previous iterator into chunks of 3: ['1', '2', '3']
  .map(&:join)   # join the sub groups into strings: "123", "456"
  .join("-")     # finally, join the resulting groups with dashes.

Without regular expressions, with step

string = '123456789'
(string.size - 3).step(1, -3) do |i|
   string.insert(i, '-')
end
puts string
Related