2010/5/27 Sourav Haldar said:
Robert said:
2010/5/26 Sourav Haldar said:
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 =3D Struct.new :idno, ...
employees =3D [ ... ]
sorted =3D employees.sort_by {|e| e.idno}
sorted =3D 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 =3D Struct.new :name, :age, :address, :idno
a =3D [
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 =A0Employee
=A0attr_accessor :name ,:age, :address, :idno
end
=A0 a =3D Array.new
=A0 e1 =3D Employee.new
=A0 e1.name =3D "Cindy"
=A0 e1.age =3D 24
=A0 e1.address =3D "Mumbai"
=A0 e1.idno =3D 121
=A0 a.push(e1) # insert the values of e1 in the array a
=A0 puts '------------------------'
=A0 e2 =3D 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.
=A0 e2.name =3D "Kennedy"
=A0 e2.age =3D 29
=A0 e2.address =3D "Kolkata"
=A0 e2.idno =3D 131
=A0 a.push(e2) =A0# insert the values of e2 in the array a
=A0 puts '------------------------'
=A0 e3 =3D Employee.new
=A0 e3.name =3D "Pearl"
=A0 e3.age =3D 35
=A0 e3.address =3D "Chennai"
=A0 e3.idno =3D 141
=A0 a.push(e3) =A0# insert the values of e3 in the array a
=A0 a.sort!{|x,y|
=A0 x.idno <=3D> y.idno
=A0 }
=A0 a.collect!{|x|puts "#{x.name} =A0#{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
--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/