我试图遍历数组@idea_benefit
,如下所示:
["happier_customers", "happier_employees", "increased_revenue", "happier_customers", "decreased_costs", "happier_customers", "increased_revenue", ]
我需要将其元素人性化并大写,如:
["Happier Customers", "Increased Revenue", ...]
我试过了:
@idea_benefit = []
@evaluations.each do |eval|
@idea_benefit << eval.benefit
@idea_benefit.flatten
end
@idea_benefit.each do |benefit|
benefit.gsub("_", " ").capitalize
end
但我无法定位单个字符串。我如何使这项工作?
答案 0 :(得分:5)
在Rails中,您可以使用humanize
和titleize
来完成。
a = ["happier_customers", "happier_employees", "increased_revenue", "happier_customers", "decreased_costs", "happier_customers", "increased_revenue" ]
a.map { |string| string.humanize.titleize }
# => ["Happier Customers", "Happier Employees", "Increased Revenue", "Happier Customers", "Decreased Costs", "Happier Customers", "Increased Revenue"]
答案 1 :(得分:3)
@idea_benefit =
@evaluations.flat_map(&:benefit).map{|e| e.gsub("_", " ").capitalize}
答案 2 :(得分:0)
您正在寻找可枚举方法map
。
@idea_benefit = []
@evaluations.each do |eval|
@idea_benefit << eval.benefit
@idea_benefit.flatten
end
desired_output = @idea_benefit.map do |benefit|
benefit.gsub("_", " ").capitalize
end
map
方法对Enumerable对象的每个元素(在您的情况下为Array)进行操作,并返回一个新的Enumerable。如果需要,块可以是多行;块的返回值(通常是最后一行的结果)是新数组中的内容。