我有一个字符串数组。例如:
array = [ "mmaciel:x:23585:591:mmaciel:/students/mmaciel:/bin/bash\n",
"nhalvors:x:20943:565:nhalvors:/students/nhalvors:/bin/bash\n",
"orodrigu:x:28260:576:orodrigu:/students/orodrigu:/bin/bash\n" ]
我想填写班级学生:
class Student
attr_accessor :user_name, :password, :uid, :gid,
:gcos_field, :directory, :shell
attr_reader :count
def initialize(data)
@user_name,@password,@uid,@gid,@gcos_field,@directory,@shell = data
@@count = defined?(@@count) ? @@count += 1 : 1
end
end
如果它只是数组的一个元素,那对我来说很简单。简单地:
data = "dputnam:x:4185:208:Douglas Vernon Putnam:/users/dputnam:/bin/bash".split(':')
s1 = Student.new(data)
但是因为我有几十个元素,所以对我来说变得复杂得多。任何帮助将不胜感激。
答案 0 :(得分:4)
array = [ "mmaciel:x:23585:591:mmaciel:/students/mmaciel:/bin/bash\n",
"nhalvors:x:20943:565:nhalvors:/students/nhalvors:/bin/bash\n",
"orodrigu:x:28260:576:orodrigu:/students/orodrigu:/bin/bash\n" ]
students = array.map { |line| Student.new(line.chomp.split(":")) }
然后students
将成为学生的集合