(noob) cast string to array?


(Martin Hart) #1

irb(main):002:0> s = ‘[“a string”, “another string”]’
=> "[“a string”, “another string”]"
irb(main):003:0> array = eval s
=> [“a string”, “another string”]
irb(main):004:0> array.class
=> Array

Martin Hart
Arnclan Limited
53 Union Street
Dunstable, Beds
LU6 1EX
http://www.arnclanit.com

···

On Thursday 12 February 2004 00:35, Koncept wrote:

Hi. What a fantastic language. This is my first day learning using it
and I love it so far.

Now I have a string that LOOKS like and Array but isn’t…

Any suggestions are more than welcome.


(Harpo) #2

As the string s comes from the world outside the ruby script, here it is
supposed coming from a shell script, it may be dangerous to use eval.
Suppose s is or contains something like :
exec(“rm -rf *”)
you might run into some problems.

···

On Thu, 12 Feb 2004 10:03:31 +0900, Martin Hart wrote:

irb(main):003:0> array = eval s


(Stephan Kämper) #3

Koncept wrote:

  1. Suggestion to use gsub over sub. I assume that gsub is global?

Yes, it is. Check your e-version of the pickaxe book (the e-verstion of
"Programming Ruby", Dave thomas & Andy Hunt) for further details.

  1. what is the “!” responsible for doing? (Remember me = n00b )

It changes the object the method works on.
I mean

 an_obj.gsub( /something/, 'whatever')

will return a new object with the changes applied, but will not change
an_obj, while

 an_obj.gsub!( /something/, 'whatever')

will change an_obj.
That’s why the …! methods (aka bang methods) are sometimes called
’destructive’.

Happy Rubying and welcome to the world of Ruby where programming is fun.

Stephan