DMH DMH - 1 month ago 8
Ruby Question

split string without brackets and ensure quotes around each word

I have strings in the following format

one-word-after-another
as an example. What I need is these to be outputted in the following format
'one', 'word', 'after', 'another'


I have tried
'one-world-after-another'.split("-")
but the output adds brackets which I dont need.

'one-world-after-another'.split("-")
=> ["one", "world", "after", "another"]


I know this is because its an Array.

Can anyone recommend a way to achieve the outcome
'one', 'word', 'after', 'another'

Answer

Something like this should work:

puts 'one-world-after-another'.split("-").map {|e| "'#{e}'"}.join(", ")

This produces:

'one', 'world', 'after', 'another'