Reputation: 163
I'm going through TestFirst.org's Ruby course, and I ran into a coding challenge that required me to construct a method "titleize" that capitalizes every word in a string except 'little words'.
The following code solves the problem.
def titleize(words)
little_words = %w[a an the and but or for nor on at to from by over]
capitalizer = Proc.new do |word|
if little_words.include? word
word
else
word.capitalize
end
end
words.split.map(&capitalizer)*' '
end
I originally tried using the following proc.
capitalizer = Proc.new { |word| little_words.include? word ? word : word.capitalize }
However, this proc only returned truth values. The truth values came from whether or not the word
being tested was included in the little_words
array. This leads me to believe that the proc is returning before it even evaluates the code to the right of the question mark.
I read the Ruby documentation for both procs and the ternary operator, but I could find nothing regarding whether or not the two can be used together.
I searched Stack Overflow for "proc ruby ternary" and read through the similar questions that popped up as I began to post this question. I couldn't find anything there either.
And so, I come to you, the geniuses of Stack Overflow. I have a question.
In Ruby, can one use a ternary operator in a proc?
(and if so, why didn't my little proc work?)
Upvotes: 0
Views: 199
Reputation: 6076
Try:
capitalizer = Proc.new { |word| little_words.include?(word) ? word : word.capitalize }
That should work.
Upvotes: 3