Ruby | The difference between first / last / begin / end / min / max
first
Return the first element. that's all.
[5,4,3,2,1].first # => 5
last
Return the last element. that's all.
[5,4,3,2,1].last # => 1
begin
Return the first element in the range. (* 2) It looks like the first version of Range.
(5..1).begin # => 5
Actually, begin is the same as first. You can write either. (* 1)
(5..1).first # => 5
But you can not use begin on ordinary arrays.
[5,4,3,2,1].begin # => NoMethodError: undefined method `begin' for [5, 4, 3, 2, 1]:Array
end
Return the last element in the range. (* 2) It looks like last in the Range version.
(5..1).end # => 1
In fact, end is the same as last. You can write either. (* 1)
(5..1).last # => 1
However, you can not use end for ordinary arrays.
[5,4,3,2,1].end # => NoMethodError: undefined method `end' for [5, 4, 3, 2, 1]:Array
min
Returns the smallest element in the array. The order of the elements does not matter.
[5,4,-3,2,1].min # => -3
max
Returns the largest element in the array. The order of the elements does not matter.
[5,4,30,2,1].max # => 30
Annotation
* 1) Strictly speaking, there is a difference between taking and not taking arguments. If you do not pass an argument will be the same behavior.
* 2) The "first element" of Range is the beginning. It is better to say that the "last element" is the end. Ruby's "scope" is relatively complicated, so please refer to the comments in this article.
Original by
Ruby | first / last / begin / end / min / max の違い
About
チャットメンバー募集
何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。
公開日時
2019-04-16
Discussion