如何用Ruby方式编写嵌套搜索?

准备好了没

我正在尝试编写快速简洁的代码。感谢您对以下代码的最佳编写方式以及原因的想法:

选项1

def get_title
  title = check_in_place_one
  if title.empty?
    title = check_in_place_two
    if title.empty?
      title = check_in_place_three
    end
  end
  return title
end

选项#2

def get_title
  title = check_in_place_one
  title = check_in_place_two unless !title.empty?
  title = check_in_place_three unless !title.empty?
  return title
end

我认为Option#1更好,因为如果通过title找到check_in_place_one,我们将测试title.empty?一次,然后跳过方法中的其余代码并返回。但是,它看起来太长了。选项#2看起来更好,但是要多处理title.empty?一个时间,而返回前会花费不必要的时间。另外,我是否缺少第三种选择?

好的

从性能上看,代码的两个版本之间没有什么区别(除了可能因解析而产生的细微差别之外,这也是可以忽略的)。控制结构相同。

从可读性上讲,如果您可以避免嵌套,那么这样做更好。您的第二个选择更好。

通常最好清除不需要进一步处理的任何情况。这是由完成的return

def get_title
  title = check_in_place_one
  return title unless title.empty?
  title = check_in_place_two
  return title unless title.empty?
  title = check_in_place_three
  return title
end

上面的代码中的最后一个title =return它们是多余的,但我将它们放在此处是为了保持一致性,从而提高了可读性。

您可以使用以下代码进一步压缩代码tap

def get_title
  check_in_place_one.tap{|s| return s unless s.empty?}
  check_in_place_two.tap{|s| return s unless s.empty?}
  check_in_place_three
end

tap这是一种非常快的方法,并且instance_eval与之不同,它的性能损失通常是可以忽略的。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何用Ruby编写IIFE?

来自分类Dev

Ruby:如果条件更好,更容易编写嵌套方式?

来自分类Dev

如何用Ruby Savon编写SOAP Authentication标头

来自分类Dev

Kotlin:如何以功能方式编写嵌套循环?

来自分类Dev

搜索嵌套的 Ruby 对象

来自分类Dev

如何以“正确的方式”用Ruby创建嵌套循环?

来自分类Dev

如何在Ruby中搜索嵌套数组?

来自分类Dev

如何用html编写分数?

来自分类Dev

如何用count编写查询

来自分类Dev

如何用PHP编写版权?

来自分类Dev

如何用ruby编写此正则表达式?(解析Gmail API字段)

来自分类Dev

Ruby遍历嵌套对象的方式

来自分类Dev

Ruby遍历嵌套对象的方式

来自分类Dev

如何用参数搜索数字?

来自分类Dev

如何用嵌套的for循环代替?

来自分类Dev

如何以功能性方式(没有可变变量)编写字母搜索功能?

来自分类Dev

如何以功能性方式编写字母搜索功能(无可变变量)?

来自分类Dev

如何用更简洁,更短而有效的方式编写具有空检查的哨兵循环?

来自分类Dev

Ruby在“ Rspec”中编写此规范的方式

来自分类Dev

如何以功能性方式有效地在嵌套集合中进行搜索

来自分类Dev

如何用Java编写Web服务

来自分类Dev

如何用Fluent语法编写HtmlHelper

来自分类Dev

如何用htaccess编写子域?

来自分类Dev

如何用PDO编写此mysql查询

来自分类Dev

如何用jekyll和redcarpet编写目录

来自分类Dev

如何用MySQL编写Golang集成测试

来自分类Dev

如何用golang编写MongoDB $ slice

来自分类Dev

如何用Java 8编写instanceof?

来自分类Dev

如何用Spring Autowire编写JUnit测试?