我正在尝试使用一些Ruby魔法重构我的代码(在它是一堆if / else-if语句之前)。但是,当我尝试在哈希中使用代码块作为我的值时,我收到以下错误:
syntax error, unexpected '}', expecting tASSOC :restaurant => { Cuisine.all },
对于下一行和(:hotel
和:attraction
)之后的行重复同样的错误。
我在这里做错了什么?
def moderation_categories(klass)
klass_map = {
:restaurant => { Cuisine.all },
:hotel => { Category.where(place_type: "Hotel") },
:attraction => { Category.where(place_type: "Attraction") }
}
list = []
klass_map[klass.to_sym].call.each { |c| list << c.name }
list.sort
end
答案 0 :(得分:4)
一个块不仅仅是一个lambda(代码块)。您必须将其指定为lambda或Proc。
klass_map = {
:restaurant => lambda{ Cuisine.all },
:hotel => lambda{ Category.where(place_type: "Hotel") },
:attraction => lambda{ Category.where(place_type: "Attraction") }
}