为什么要避免Ruby中的then关键字? [英] Why should you avoid the then keyword in Ruby?

查看:132
本文介绍了为什么要避免Ruby中的then关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在几个Ruby风格指南中提到,你应该从不使用。就个人而言,我认为then关键字允许你使代码更密集,这往往更难阅读。

It's mentioned in several Ruby style guides that you should "Never use then." Personally, I think the "then" keyword allows you to make code denser, which tends to be harder to read. Is there any other justification for this recommendation?

编辑:以下是一个指南的示例,它提供了这样的建议:http://cheat.errtheblog.com/s/styleguide/

Here is an example of one guide that makes such a recommendation: http://cheat.errtheblog.com/s/styleguide/

推荐答案

我几乎从不使用,然后关键字。然而,有一种情况,我相信它大大提高了可读性。考虑以下多条件if语句。

I almost never use the then keyword. However, there is one case where I believe it greatly improves readability. Consider the following multi conditional if statements.

示例A

if customer.jobs.present? && customer.jobs.last.date.present? && (Date.today - customer.jobs.last.date) <= 90
  puts 'Customer had a job recently'
end

线路长度太长。难以阅读。

Line length too long. Hard to read.

示例B

if customer.jobs.present? &&
   customer.jobs.last.date.present? &&
   (Date.today - customer.jobs.last.date) <= 90
  puts 'Customer had a job recently'
end

条件结束和内部代码在哪里开始。根据Ruby Style Guide,你必须为多行条件语句留出一个额外的缩进空间,但是我还是觉得不容易阅读。

Where do the conditions end and where does the inner code begin. According to must Ruby Style Guides, you to have one extra space of indentation for multi line conditionals, but I still don't find it all the easy to read.

示例C

if customer.jobs.present? &&
   customer.jobs.last.date.present? &&
   (Date.today - customer.jobs.last.date) <= 90
then
  puts 'Customer had a job recently'
end

对我来说,示例C是最清楚的。它是使用然后做的伎俩。

To me, Example C is by far the most clear. And it is the use of the then that does the trick.

这篇关于为什么要避免Ruby中的then关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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