Project

General

Profile

Actions

Feature #12059

open

`Array#single?`, `Hash#single?`

Added by sawa (Tsuyoshi Sawada) about 8 years ago. Updated about 8 years ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:73748]

Description

There are some use cases when one wants to check if an array or a hash has exactly one element. I propose Array#single? and Hash#single? that checks for such cases and returns either true or false. This is an analogy from the empty? method on the respective class.

  • When creating an inflectional form out of an array:
a = ["object1", "object2"]
"There #{a.single ? "is" : "are"} #{a.length} #{a.single? ? "object" : "objects"}."
# => "There are 2 objects."
  • When checking if all elements of the array are the same:
[1, 2, 2, 1].uniq.single? # => false
[1, 1, 1, 1].uniq.single? # => true
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0