Getting rid of double quotes inside array without turing array into a string [closed]

被刻印的时光 ゝ 提交于 2020-01-06 03:55:13

问题


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!


回答1:


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



回答2:


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.




回答3:


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).



来源:https://stackoverflow.com/questions/20834334/getting-rid-of-double-quotes-inside-array-without-turing-array-into-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!