从数组返回特定的字符串格式
Returning a specific string format from an array
我有一个 Persons 数组(class 包含 name 和 lastname 以及 id )
我要做的是 return 一个字符串形成这个数组,但在特定格式中,一个例子会更明确
array=[PERS1,PERS2]
我需要这个作为 return 值:“所有人的姓名:”+ PERS1.name + PERS1.LASTN + “,” + PERS2.name +PERS2.LASTN +","
我知道这个方法
array.each{ |per|
#but this will not return the format ,and with each I think I can only print (I'm new in the ruby field
}
所有这些都是因为我在覆盖 to_s 时需要它,因为我需要提供一个字符串 -> to_s
def to_s
"THE name of all preson"+@array.each #will not work as I want
end
感谢您付出的时间和精力,如果您需要任何说明,请告诉我
试试这个,
array.each do |per|
"#{per.name} #{per.LASTN}"
end
更多信息请查看Interpolation
each
just iterates over a collection and returns the collection itself. You may want to use map
and join
结果。
array.map { |person| "#{person.name} #{person.lastn}" }.join(',')
或者如果你修改你的 Person
class 它可以更简单。
# I assume that the name of the class is Person and name and lastn are always present
class Person
def full_name
"#{person.name} #{person.lastname}"
end
end
# Then you can call this method on `map`.
array.map(&:full_name).join(',')
我有一个 Persons 数组(class 包含 name 和 lastname 以及 id ) 我要做的是 return 一个字符串形成这个数组,但在特定格式中,一个例子会更明确
array=[PERS1,PERS2]
我需要这个作为 return 值:“所有人的姓名:”+ PERS1.name + PERS1.LASTN + “,” + PERS2.name +PERS2.LASTN +","
我知道这个方法
array.each{ |per|
#but this will not return the format ,and with each I think I can only print (I'm new in the ruby field
}
所有这些都是因为我在覆盖 to_s 时需要它,因为我需要提供一个字符串 -> to_s
def to_s
"THE name of all preson"+@array.each #will not work as I want
end
感谢您付出的时间和精力,如果您需要任何说明,请告诉我
试试这个,
array.each do |per|
"#{per.name} #{per.LASTN}"
end
更多信息请查看Interpolation
each
just iterates over a collection and returns the collection itself. You may want to use map
and join
结果。
array.map { |person| "#{person.name} #{person.lastn}" }.join(',')
或者如果你修改你的 Person
class 它可以更简单。
# I assume that the name of the class is Person and name and lastn are always present
class Person
def full_name
"#{person.name} #{person.lastname}"
end
end
# Then you can call this method on `map`.
array.map(&:full_name).join(',')