From: Robert Klemme Date: 2010-05-27T18:47:47+09:00 Subject: Re: Regarding Arrays 2010/5/27 Sourav Haldar : > Robert Klemme wrote: >> 2010/5/26 Sourav Haldar : >>> >>> I am trying to build a Class 'Employee' in which age,address,idno >>> methods should be there . So i need to built a Array in which the >>> elements are called by idno and get sorted. >> >> Not sure what you're after, probably something like this >> >> Employee = Struct.new :idno, ... >> >> employees = [ ... ] >> sorted = employees.sort_by {|e| e.idno} >> sorted = employees.sort_by(&:idno) # alternative > I have built a program but wants to make it more short . SO plz see > wether is it possible or not It is. Employee = Struct.new :name, :age, :address, :idno a = [ Employee["Cindy", 24, "Mumbay", 121], Employee["Kennedy", 29, "ruby-talk", 131], ] a.sort_by(&:idno).each do |x| puts x.map(&:to_s).join(" ") end :-) > class  Employee >  attr_accessor :name ,:age, :address, :idno > end > >   a = Array.new >   e1 = Employee.new >   e1.name = "Cindy" >   e1.age = 24 >   e1.address = "Mumbai" >   e1.idno = 121 >   a.push(e1) # insert the values of e1 in the array a >   puts '------------------------' >   e2 = Employee.new You do not need a new local variable here: you can reuse "e1" since the object created above is in the Array already. >   e2.name = "Kennedy" >   e2.age = 29 >   e2.address = "Kolkata" >   e2.idno = 131 >   a.push(e2)  # insert the values of e2 in the array a >   puts '------------------------' >   e3 = Employee.new >   e3.name = "Pearl" >   e3.age = 35 >   e3.address = "Chennai" >   e3.idno = 141 >   a.push(e3)  # insert the values of e3 in the array a > >   a.sort!{|x,y| >   x.idno <=> y.idno > >   } > >   a.collect!{|x|puts "#{x.name}  #{x.age} #{x.address} #{x.idno}"} You should use #each here instead of #collect! because I believe you only want to output all elements in the Array but not change the Array itself. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/