如何缩进...是否...结束...结束 [英] How to indent if...any...do...end...end

查看:94
本文介绍了如何缩进...是否...结束...结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是红宝石的新手,我想知道您如何缩进这段代码:

I am new to ruby and I wonder how you would indent this code:

if a.any? do |blah|
name = blah[:name][/.* (.*)/, 1]
name = convert_name(name)
text = "#{name}#{blah[:value]}"
text == "b2"
end
puts "found"
exit 1
end

推荐答案

我会这样写:

if a.any? { |blah| (blah[:name] + blah[:value]) == "b2" }
  puts "found"
  exit 1
end

或者:

if a.any? { |blah| blah.values_at(:name, :value).join == "b2" }
  puts "found"
  exit 1
end

实际测试足够短,可以在一行中完成.

The actual test is short enough that it can be done in a single line.

通常,当块返回值或在一行上时,我们对它们使用大括号({}).

Generally we use braces ({}) for blocks when they return a value or are on a single line.

将两个字符串插值到另一个字符串中只是为了将它们连接起来很臭.只是将它们串联起来;更明显的是您在做什么.

Interpolating two strings in another string just to join them is smelly. Just concatenate them; It's more obvious what you're doing.

如果您担心如何清楚地缩进,请考虑以下事项:

If you're ONLY concerned about how to indent clearly, consider this:

if a.any? do |blah|
    name = blah[:name][/.* (.*)/, 1]
    name = convert_name(name)
    text = "#{name}#{blah[:value]}"
    text == "b2"
  end
  puts "found"
  exit 1
end

any?块的缩进应比if块的内容缩进更多,以便在视觉上将它们分开.除了缩进之外,还应该将any? 的代码块重构为一行.

The any? block should be indented further than the contents of the if block to visually separate them. Beyond the indention... ugh... the code block for any? should be refactored to a single line still.

这篇关于如何缩进...是否...结束...结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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