(noob) cast string to array?

(David A. Black) #1

Hi –

In article
XOCWb.33248$TPZ.8375@twister01.bloor.is.net.cable.rogers.com, Mike

Alternatively, if the data is “well behaved”, you can use a regular
expression to pick it apart. Using irb (interactive ruby to experiment:

result = ‘{ “robert”, “trey”, “adrian”, “pat” }’
=> “{ “robert”, “trey”, “adrian”, “pat” }”

=> [“robert”, “trey”, “adrian”, “pat”]

Forgive me if I am missing something…

You are missing something, and I forgive you :slight_smile:

irb(main):001:0> result = ‘{ “robert”,“trey”,“adrian”, “pat” }’
=> “{ “robert”,“trey”,“adrian”, “pat” }”

irb(main):002:0> result.scan(/"(.*?)"/).flatten
=> [“robert”, “trey”, “adrian”, “pat”]

irb(main):004:0> result.class
=> String

irb(main):005:0> result = [“robert”,“trey”,“adrian”,“pat”]
=> [“robert”, “trey”, “adrian”, “pat”]

irb(main):006:0> result.class
=> Array

Your solution formatted my string to look like an Array, but the result
still has a class of String. :frowning:

How can I cast this String as an Array?

You can’t (no such thing), but you can achieve what you need by saving
the results of your scan operation:

result_array = result.scan(/"(.*?)"/).flatten

or if you want to re-use the same variable name:

result = result.scan(etc…)

Right now you’re performing a scan and then discarding the resulting



On Fri, 13 Feb 2004, Koncept wrote:

Stok mike@stok.co.uk wrote:

David A. Black