문제

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