1

Looking over this bit of code here:

class Book
  def title
    @title
  end

  def title=(title)
    @title = titlieze(title)
  end

  private
  def titlieze(title)
    stop_words = %w(and in the of a an)
    title.capitalize.split.map{|w| stop_words.include?(w) ? w : w.capitalize}.join(' ')
  end
end

I am very confused about what is going on with the ? after the include? in #map - is this an operator or a method shortcut?

Also wondering what exactly the : is called in this case, and what it does.

Thanks!

1 Answers1

2

It's a ternary operator. It signifies a ternary operation, which acts essentially as an if-else statement. So this:

stop_words.include?(w) ? w : w.capitalize

Essentially becomes this:

if stop_words.include?(w)
    return w
else
    return w.capitalize
end

Here's how I think of a ternary operation:

(<if condition>) ? <thing to do if true> : <thing to do if false>
Undo
  • 25,519
  • 37
  • 106
  • 129