尝试查找有关 ruby​​ 尾随使用情况的文档 [英] trying to find documentation on ruby's trailing if usage

查看:20
本文介绍了尝试查找有关 ruby​​ 尾随使用情况的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究 RSpec 书籍(第 121 页),并看到了一些显然不言自明和清晰的代码.这对我来说不是不言而喻的,我希望有人能帮助我理解.

I'm working in the RSpec book (page 121) and am being presented with a bit of code that is apparently self evident and clear. It's not self evident for me, and I'm hoping someone can help me understand.

我从 c# 开始使用 ruby​​,所以请使用小词 :)

I'm coming to ruby from c# so please use small words :)

这是原始代码

def total_match_count
    count = 0
    secret = @secret.split('')
    @guess.split('').map do |n|
        if secret.include?(n)
            secret.delete_at(secret.index(n))
            count += 1
        end
    end
    count
end

这里是重构

def total_match_count
    secret = @secret.split('')
    @guess.split('').inject(0) do |count, n|
        count + (delete_first(secret, n) ? 1 : 0)
    end
end

def delete_first(code, n)
    code.delete_at(code.index(n)) if code.index(n)
end

再说一次,这应该是显而易见的,不需要评论.我不理解尾随的if code.index(n)"位,我找不到任何关于使用关键字ruby trailing if"的文档

Again, this is supposed to be so obvious as to need no comment. I'm not understanding the trailing "if code.index(n)" bit and I can't find any documentation on using the keywords "ruby trailing if"

显然我遗漏了一些基本的东西.

Obviously I'm missing something basic.

推荐答案

Ruby Post-Conditions as Syntactic Sugar

在 Ruby 中,几乎所有东西都是表达式,像 ifunless 这样的关键字可以用作 表达式修饰符跟随一个表达式.一些语言将这些称为后置条件,但总体思路是:

Ruby Post-Conditions as Syntactic Sugar

In Ruby, almost everything is an expression, and keywords like if and unless can be used as expression modifiers that follow an expression. Some languages refer to these as post-conditions, but the general idea is that:

if 1 == 1
  puts true
end

旨在等同于:

puts true if 1 == 1

后置条件有时可以使代码的意图更清晰,或者创建更自然的流程.解析器区分 :if 和 :if_mod 标记,它们在内部表示正常"的 if 语句及其匹配的后置条件,但从程序员的角度来看,后置条件是(或应该是)主要用于生成某些表达式的语法糖更易于阅读和书写.

The post-condition can sometimes make the intent of the code clearer, or create a more natural flow. The parser differentiates between the :if and :if_mod tokens that internally represent the "normal" if-statement and its matching post-condition, but from a programmer's perspective the post-conditions are (or should be) largely syntactic sugar to make certain expressions easier or cleaner to read and write.

在 Ruby 中您永远需要后置条件,但您经常会在惯用的 Ruby 代码中找到它们.如果您不理解它们,或者没有发现它们提高了代码的可读性,那么请随意忽略它们,直到它们对您有用为止.

You don't ever need post-conditions in Ruby, but you will often find them in idiomatic Ruby code. If you don't grok them, or don't find that they improve the readability of your code, then feel free to ignore them until and unless they seem useful to you.

这篇关于尝试查找有关 ruby​​ 尾随使用情况的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆