什么是`#数组包含?`比`阵列#index`的目的是什么? [英] What is the purpose of `Array#include?` as compared to `Array#index`?

查看:203
本文介绍了什么是`#数组包含?`比`阵列#index`的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阵列#包括哪些内容?仅提供比阵列#指数提供了一个较弱的信息,即,当阵列#指数收益阵列#包括哪些内容?将返回,并在阵列#指数返回一个整数,阵列#包括?收益真正。此外,比较这两个表示有在速度无显著差异;而阵列#指数往往表现出比阵列#包括一个更好的结果

Array#include? provides only a weaker information than what Array#index provides, i.e., when Array#index returns nil, the corresponding method call with Array#include? will return false, and when Array#index returns an integer, Array#include? returns true. Furthermore, comparing the two indicates that there is no significant difference in speed; rather Array#index often shows a better result than Array#include?:

a = %w[boo zoo foo bar]

t = Time.now
10000.times do
  a.include?("foo")
end
puts Time.now - t # => 0.005626235

t = Time.now
10000.times do
  a.index("foo")
end
puts Time.now - t # => 0.003683945

那么,什么是的目的阵列#包括哪些内容??不能所有code。使用它使用重写阵列#指数

Then, what is the purpose of Array#include?? Can't all code using it be rewritten using Array#index?

推荐答案

我知道这是不是一个正式的原因,但我能想到的几件事情:

I know this isn't an official reason, but I can think of a few things:


  • 净度:作为名字,包括哪些内容?更有意义一见钟情,并且还允许code正确性的快捷判定通过识别本身作为一个布尔值predicate。在此之前,作出错误的code样子错误的概念(见 HTTP://www.joelonsoftware。 COM /用品/ Wrong.html

  • 好打字:如果你想要的是一个布尔检查一个布尔值,使得这一个数字可能会导致错误

  • 清洁度:是不是更好看真打印输出,而不是要回C和无布尔可言

这篇关于什么是`#数组包含?`比`阵列#index`的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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