I have an array

x=["1", "2", "3", ":*", ":+", "4", "5", ":-", ":/"]

I'm trying to get rid of the double quotation inside of the array.

I know I can use:

x.to_s.gsub('"','')

and it will output a string:

"[1, 2, 3, :*, :+, 4, 5, :-, :/]"

The desired output I want is an array not a string:

[1, 2, 3, :*, :+, 4, 5, :-, :/]

Is there a way for me to get rid of the double quotes for each element of the array but still leave my array as an array?

Thanks in advance!

有帮助吗?

解决方案

eval x.to_s.gsub('"', '')
# => [1, 2, 3, :*, :+, 4, 5, :-, :/]

其他提示

Here is one way you can do it:

x=["1", "2", "3", ":*", ":+", "4", "5", ":-", ":/"]
=> ["1", "2", "3", ":*", ":+", "4", "5", ":-", ":/"]

x.map{|n|eval n}
=> [1, 2, 3, :*, :+, 4, 5, :-, :/]

Important: The eval method is unsafe if you are accepting unfiltered input from an untrusted source (e.g. user input). If you are crafting your own array of strings, then eval is fine.

x = ["1", "2", "3", ":*", ":+", "4", "5", ":-", ":/"]

x.map {|e| e[0] == ':' ? e[1..-1].to_sym : e.to_i}

or

x.map {|e| (e =~ /^\d+$/) ? e.to_i : e[1..-1].to_sym}

  # => [1, 2, 3, :*, :+, 4, 5, :-, :/] 

This of course only works when the elements of x are quoted integers and symbols (and I prefer the use of eval).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top