更优雅的方式在ruby中编写多维字符数组?

时间:2010-05-18 04:11:32

标签: ruby

我正在尝试在ruby中创建一个多维数组的字符,这样可行,但是有更优雅的方式吗?

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 个答案:

答案 0 :(得分:7)

@map = text.split("\n").map{|x| x.scan(/./)}

#looks slightly better, needs at least 1.8.7
@map = text.lines.map{|x| x.scan(/./)} 

答案 1 :(得分:3)

@map = text.lines.to_a.map { |s| s.chomp.split("") }