我有一個 Persons 陣列(類包含 name 和 lastname 和 id )我要做的是從這個陣列回傳一個字串,但是以特定格式,一個例子會更明確
array=[PERS1,PERS2]
我需要這個作為回傳值:“所有人的名字:“ 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
感謝您的時間和精力,如果您需要任何澄清,請告訴我
uj5u.com熱心網友回復:
each只是迭代一個集合并回傳集合本身。您可能想要使用map和join結果。
array.map { |person| "#{person.name} #{person.lastn}" }.join(',')
或者如果你修改你的Person類,它可以更簡單。
# 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(',')
uj5u.com熱心網友回復:
嘗試這個,
array.each do |per|
"#{per.name} #{per.LASTN}"
end
有關更多資訊,請檢查插值
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/446677.html
