我想通过调用类方法将实例的名称存储在数组中。
当我尝试时,它返回整个实例。当我放object_id
时,它返回我的对象的整数标识符。我想要一个数组中实例的名称,稍后我想要用last_name
对对象进行排序。
我试过了:
class Person
attr_accessor :name, :years, :height, :work, :last_name
@@people=[]
def initialize(name)
@name=name
@@people << self #WHAT TO TYPE HERE???
end
def <=> (other_person) # to compare two people, use last names
self.last_name <=> other_person.last_name
end
def self.number_of_instances
return @@people
end
end
mike=Person.new("michael")
mike.years=45
mike.height=141
mike.work="singer"
mike.last_name="zux"
bob=Person.new("boby")
bob.years=29
bob.height=150
bob.work="soldier"
bob.last_name="awax"
steven=Person.new("stephan")
steven.years=24
steven.height=179
steven.work="painter"
steven.last_name="sigal"
elena=Person.new("eli")
elena.years=20
elena.height=171
elena.work="menager"
elena.last_name="betany"
a= Person.number_of_instances
sorted_names= a.sort!{|first,second| first<=>second }
p sorted_names
预期输出应按其last_name
:
[bob, elena, steven, mike]
有没有办法存储我分配给整个对象的名称,如bob
,elena
,steven
,mike
?
答案 0 :(得分:1)
如果要将名称放在数组中,则只需将名称放在数组中:
@@people << name
答案 1 :(得分:0)
class Person
attr_accessor :name, :last_name
def initialize(name)
@name = name
@last_name = ""
end
end
class Team
attr_accessor :team
def initialize
@team = []
end
def <<(person)
team.push(person)
end
def people_by_last_name
team.sort_by { |person| person.last_name }.map(&:name)
end
end
team = Team.new
person = Person.new("Mark")
person.last_name = "Davids"
team << person
person = Person.new("John")
person.last_name = "Stephenson"
team << person
puts team.people_by_last_name