0

I'm trying to iterate through an array @idea_benefit which looks like this:

["happier_customers", "happier_employees", "increased_revenue", "happier_customers", "decreased_costs", "happier_customers", "increased_revenue", ]

I need its elements to be humanized and capitalized like:

["Happier Customers", "Increased Revenue", ...]

I tried this:

@idea_benefit = []
@evaluations.each do |eval|
  @idea_benefit << eval.benefit
  @idea_benefit.flatten
end
@idea_benefit.each do |benefit|
  benefit.gsub("_", " ").capitalize
end

but I could not target the individual strings. How do I make this work?

1
  • but I've been unsuccessful targeting the individual strings could you please elaborate that part with an example? Commented Jun 18, 2015 at 4:19

3 Answers 3

7

In Rails, you can do it using humanize and 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"]
Sign up to request clarification or add additional context in comments.

Comments

3
@idea_benefit =
@evaluations.flat_map(&:benefit).map{|e| e.gsub("_", " ").capitalize}

1 Comment

Beautiful. This does only capitalize the first word though (i.e. "Increased revenue" instead of "Increased Revenue"). Is there a way to capitalize both?
0

You're looking for the Enumerable method 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

The map method operates on each element of an Enumerable object (an Array, in your case) and returns a new Enumerable. The block could be multiple lines if you needed; the return value of the block (usually the result of the last line) is what goes in the new array.

2 Comments

this gives me the error undefined method gsub' for ["happier_customers", "happier_employees", "increased_revenue"]:Array`
I'm assuming you've already flattened the array. I edited in the rest of your code to make it a little clearer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.