How do I create instances of a Ruby class from data in an array? -
i've got array of strings. example:
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" ] and want populate class student:
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 if it's 1 element of array, it's simple me. simply:
data = "dputnam:x:4185:208:douglas vernon putnam:/users/dputnam:/bin/bash".split(':') s1 = student.new(data) but since have array of dozens of elements, becomes more complicated me. appreciated.
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(":")) } then students collection of students
Comments
Post a Comment