【问题标题】:What is this '?' operator in #map doing? [duplicate]这是什么 '?' #map 中的运算符在做什么? [复制]
【发布时间】:2023-03-05 13:59:01
【问题描述】:

在这里查看这段代码:

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

我对 ?#map 中的 include? 之后发生了什么感到非常困惑 - 这是运算符还是方法快捷方式?

还想知道在这种情况下,: 究竟被称为什么,以及它的作用。

谢谢!

【问题讨论】:

  • 嗯,它是 a 三元运算符,特别是条件运算符。

标签: ruby map operator-keyword


【解决方案1】:

这是一个三元运算符。它表示ternary operation,它本质上是一个 if-else 语句。所以这个:

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

基本上变成了这样:

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

这是我对三元运算的看法:

(<if condition>) ? <thing to do if true> : <thing to do if false>

【讨论】:

  • "turnery" != "ternary"
  • 很高兴@theTinMan,谢谢 ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-29
  • 2013-02-25
  • 2021-02-26
  • 2015-10-20
  • 1970-01-01
  • 1970-01-01
  • 2020-08-26
相关资源
最近更新 更多