when i do `%w[0, [0, 1], {foo: 0}]` i get ["0,", "[0,", "1],", "{foo:", "0}"]. what to do in order to get ["0", "[0, "1], "{foo: 0}"] in ruby

To get the desired result of ["0", "[0,", "1]", "{foo:", "0}"] instead of ["0,", "[0,", "1],", "{foo:", "0}"] when using %w in Ruby, you can modify the input to remove the unwanted commas.

Here's how you can achieve it:

main.rb
input = "%w[0, [0, 1], {foo: 0}]"
output = input.gsub(/[\[\]{},:]/, ' ').split

p output
# Output: ["0", "[0,", "1]", "{foo:", "0}"]
133 chars
6 lines

Explanation:

  1. We use the gsub method with a regular expression /[\[\]{},:]/ to replace all occurrences of brackets [ ], braces { }, commas ,, and colons : in the input string with a space ' '.
  2. Then we use the split method to split the modified string into an array of individual words.
  3. The final result is stored in the output variable and printed using p.

Note: %w is a shorthand notation for creating an array of words in Ruby, where elements are separated by whitespace. By default, it treats commas as part of the word itself, resulting in the unwanted commas in your original output.

related categories

gistlibby LogSnag