tags:

views:

123

answers:

2

Hi,

I am trying to make a multi-dimensional array of characters in ruby, and this works, but is there a more elegant way?

def initialize(text)
    @map = Array.new
    i = 0
    text.split("\n").each do |x|
     @map[i] = x.scan(/./)
     i += 1
    end
    #@map = text
  end#constructor
+2  A: 
@map = text.lines.to_a.map { |s| s.chomp.split("") }
yjerem
`map` defined on `Enumerable`
vava
+7  A: 
@map = text.split("\n").map{|x| x.scan(/./)}

#looks slightly better, needs at least 1.8.7
@map = text.lines.map{|x| x.scan(/./)} 
vava
... at least 1.8.7, or else `require 'backports'`. Yet another way: `text.lines.map{|x| x.chars.to_a}`
Marc-André Lafortune
@Marc, that leaves '\n' in result
vava
Most excellent. I knew I was being verbose. Ruby can be elegant, but you really have to know what you are doing!
tesmar