【问题标题】:Need a ruby block explained [duplicate]需要一个红宝石块解释[重复]
【发布时间】:2015-06-06 20:40:32
【问题描述】:

我想知道是否有人可以向我解释一下

? w : w.大写

block 表示在:

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

非常感谢任何帮助...提前谢谢您。

【问题讨论】:

  • 这个post解释了这个三元运算符

标签: ruby-on-rails ruby


【解决方案1】:

那里是ternary operator。这个:

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

意思相同:

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

【讨论】:

  • 非常感谢@Tiago 又一个精彩的解释!!
【解决方案2】:

通常在英语语法中,如果我们将句子中每个单词的首字母大写,那么我们将这些单词保留为小写字母

单词:and, in, the, of, a, an

所以在 ruby​​ 的 titlieze 方法中,它只是确保忽略给定句子中的这些单词。所以下面的特定条件只是一个 IF ELSE 而不是别的

stop_words.include?(w) ? w : w.大写

这意味着如果 w (被处理的单词) 存在于忽略单词 stop_words (and, in, the, of, a, an) 的数组中,那么就让它小写,否则将单词的第一个字母大写.

【讨论】:

  • 很好的答案,非常感谢。
【解决方案3】:

这是Ternary Operator

对于title 中的每个单词w,如果w 包含在stop_words 中,则返回w 否则大写w 并将其返回给映射器。

【讨论】:

    猜你喜欢
    • 2011-02-12
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 2014-06-15
    • 2018-05-17
    • 2012-07-20
    • 2017-04-18
    • 1970-01-01
    相关资源
    最近更新 更多