开发者

Convert a String Containing an Array to an Array in Ruby

开发者 https://www.devze.com 2022-12-21 07:15 出处:网络
I have a string that contains an array that i would like to convert into an array. How would you do this?

I have a string that contains an array that i would like to convert into an array. How would you do this?

I want to convert this:

myvar=
"[[Date.UTC(2010, 0, 23),0],[Date.UTC(2010, 0, 24),0],[D开发者_如何学JAVAate.UTC(2010, 0, 25),3],[Date.UTC(2010, 0, 26),0],[Date.UTC(2010, 0, 27),0],[Date.UTC(2010, 0, 28),0],[Date.UTC(2010, 0, 29),0],[Date.UTC(2010, 0, 30),0],[Date.UTC(2010, 0, 31),0],[Date.UTC(2010, 1, 01),0],[Date.UTC(2010, 1, 02),0],[Date.UTC(2010, 1, 03),1],[Date.UTC(2010, 1, 04),2],[Date.UTC(2010, 1, 05),0],[Date.UTC(2010, 1, 06),0],[Date.UTC(2010, 1, 07),0],[Date.UTC(2010, 1, 08),0],[Date.UTC(2010, 1, 09),0],[Date.UTC(2010, 1, 10),0],[Date.UTC(2010, 1, 11),0],[Date.UTC(2010, 1, 12),0],[Date.UTC(2010, 1, 13),0],[Date.UTC(2010, 1, 14),0],[Date.UTC(2010, 1, 15),0],[Date.UTC(2010, 1, 16),0],[Date.UTC(2010, 1, 17),0],[Date.UTC(2010, 1, 18),0],[Date.UTC(2010, 1, 19),0],[Date.UTC(2010, 1, 20),0],[Date.UTC(2010, 1, 21),0]]"
myvar.class
>>string

Into This:

myvar = 
[[Date.UTC(2010, 0, 23),0],[Date.UTC(2010, 0, 24),0],[Date.UTC(2010, 0, 25),3],[Date.UTC(2010, 0, 26),0],[Date.UTC(2010, 0, 27),0],[Date.UTC(2010, 0, 28),0],[Date.UTC(2010, 0, 29),0],[Date.UTC(2010, 0, 30),0],[Date.UTC(2010, 0, 31),0],[Date.UTC(2010, 1, 01),0],[Date.UTC(2010, 1, 02),0],[Date.UTC(2010, 1, 03),1],[Date.UTC(2010, 1, 04),2],[Date.UTC(2010, 1, 05),0],[Date.UTC(2010, 1, 06),0],[Date.UTC(2010, 1, 07),0],[Date.UTC(2010, 1, 08),0],[Date.UTC(2010, 1, 09),0],[Date.UTC(2010, 1, 10),0],[Date.UTC(2010, 1, 11),0],[Date.UTC(2010, 1, 12),0],[Date.UTC(2010, 1, 13),0],[Date.UTC(2010, 1, 14),0],[Date.UTC(2010, 1, 15),0],[Date.UTC(2010, 1, 16),0],[Date.UTC(2010, 1, 17),0],[Date.UTC(2010, 1, 18),0],[Date.UTC(2010, 1, 19),0],[Date.UTC(2010, 1, 20),0],[Date.UTC(2010, 1, 21),0]]
myvar.class
>>Array


While the obvious answer involves eval, this is dangerous. I would instead recommend parsing it. Since this is quite a well defined data format (it seems), you can use this:

myvar.scan(/\d+/).map(&:to_i).each_slice(4).map{|*x,y| [Date.UTC(*x), y]}

this will

  • pull out all the digits
  • convert them to integers
  • separate them into groups of four
  • apply the first three of each group to Date.UTC as the first through third arguments
  • pair each date with its corresponding y
  • create an array containing all of these pairs.

I don't have a Date.UTC method, but I assume you have some custom method called that.


try eval command

x = eval("[\"foo\",\"bar\",\"land\"]")

=> ["foo", "bar", "land"]

x

=> ["foo", "bar", "land"]

but eval is danger be care full when use it.

0

精彩评论

暂无评论...
验证码 换一张
取 消