(noob) cast string to array?

David Naseby [mailto:david.naseby@eonesolutions.com.au] humbly suggested:

c:\family\ruby>cat a1.rb
s = “{‘this’,‘is a’,‘test of wits’}” # just a string
t = s.gsub(/[{}]/,‘’) # no more {}
u = t.split(‘,’).to_a #
convert to array
puts “u is of class #{u.class}”
u.each_index {|i| puts “#{i} #{u[i]}”}

I used each_index just in case you’ll doubt if it’s really an
array. note,
no eval there :slight_smile:

Or easier, avoiding eval again:

u = s.scan( /[\w\s]+/ )

wow. thanks for the tip, david.

fr here:
s = “{‘this’,‘is a’,‘test of wits’}” # just a string
t = s.gsub(/[{}]/,‘’) # no more {}
u = t.split(‘,’).to_a #
puts “u is of class #{u.class}”
u.each_index {|i| puts “#{i} #{u[i]}”}

to here:
s = “{‘this’,‘is a’,‘test of wits’}”
u = s.scan(/[\w\s]+/)
puts “u is of class #{u.class}”
u.each_index {|i| puts “#{i} #{u[i]}”}

btw, I have a personal dislike for scan. Scan is too generic a name and the
method returns two kinds of output (array or string) depending on how you
use it.

As a result, I have created 2 sibling methods for scan:

scan_toa #returns array, no block; method errs if block is passed
scan_tostring #returns string, with block; method errs if block isn’t passed

David

kind regards -botp