我想重构一下:
class Collection
def artists
@songs.map { |song| song.artist }.uniq
end
def albums
@songs.map { |song| song.album }.uniq
end
def names
@songs.map { |song| song.name }.uniq
end
end
这样的事情:
class Collection
song_attributes = [:artist, :album, :name]
song_attributes.each do |song_attribute|
define_method song_attribute do
@songs.map { |song| song.public_send(song_attribute) }.uniq
end
end
end
问题在于行define_method song_attribute do
,其中song_attribute
必须是多元化的。我该怎么做?
我只是想出了这个,但我想有更好的方法:
song_attributes = [[:artists, :artist], [:albums, :album], [:names, :name]]
song_attributes.each do |song_attribute|
define_method song_attribute[0] do
@songs.map { |song| song.public_send(song_attribute[1]) }.uniq
end
end
答案 0 :(得分:2)
.....
song_attributes = [:artist, :album, :name]
song_attributes.each do |song_attribute|
define_method("#{song_attribute}s") do
@songs.map { |song| song.public_send(song_attribute) }.uniq
end
end
.....