Ruby convention for accessing first/last element in array [closed]

守給你的承諾、 提交于 2019-12-05 00:33:45

Code is read more than it is written, and first and last take less effort to understand, especially for a less experienced Ruby programmer or someone from a language with different indexing semantics.

While most programmers will immediately know that these are the same:

a.first
a[0]

the first still reads more easily. There isn't a marked difference in how hard it is to read, but it's there.

last is another issue. Accessing the index 0 will get you the first element of an array in almost any language. But negative indexing is only available in some languages. If a C programmer with minimal Ruby experience is trying to read my code, which will they understand faster?:

a.last
a[-1]

The negative index will probably force them to do a Google search.

benbot

Since Matz designed Ruby after a few other languages, I think the conventions come from those other languages.

In Lisp, one of Ruby's inspirational parents, you would use something close to the last and first methods so I'll say last and first is convention.

I only really use first and last. I see many programs out there that use those methods but ultimately it is your choice. That's the beauty of Ruby ;)

From the point of view of the speed, for larger arrays, first and last are faster than []. For smaller arrays it is the other way around.

Large array:

array = (0..100000000).to_a

t = Time.now
10.times{array[0]}
puts Time.now - t
# => 0.000225356

t = Time.now
10.times{array.first}
puts Time.now - t
# => 2.9736e-05

t = Time.now
10.times{array[-1]}
puts Time.now - t
# => 7.847e-06

t = Time.now
10.times{array.last}
puts Time.now - t
# => 6.174e-06

Small array:

array = (0..100).to_a

t = Time.now
10.times{array[0]}
puts Time.now - t
# => 4.403e-06

t = Time.now
10.times{array.first}
puts Time.now - t
# => 5.933e-06

t = Time.now
10.times{array[-1]}
puts Time.now - t
# => 4.982e-06

t = Time.now
10.times{array.last}
puts Time.now - t
# => 5.411e-06

For ease of writing/reading, first and last can be used without arguments, unlike [], so they are simpler.

Sometimes, using first and last makes things easier, while it is difficult with []: e.g., array.each_slice(3).map(&:first).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!