Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Creating a non-empty array in Ruby
class NonEmptyArray
include Enumerable
def initialize(first, rest)
@first = first
@rest = rest
end
def first
@first
end
def last
@rest.last || @first
end
def each(&block)
yield @first
@rest.each(&block)
self
end
end
# [1] pry(main)> array = NonEmptyArray.new(1, [2,3,4])
# [2] pry(main)> array.first
# => 1
# [3] pry(main)> array.last
# => 4
# => #<NonEmptyArray:0x00007fcb6db57490 @first=1, @rest=[2, 3, 4]>
# [4] pry(main)> array.each { |n| puts n }
# 1
# 2
# 3
# 4
# => #<NonEmptyArray:0x00007fb3eca3c918 @first=1, @rest=[2, 3, 4]>
# [5] pry(main)> array.map { |n| n * 2 }
# => [2, 4, 6, 8]
# [6] pry(main)> array.select(&:even?)
# => [2, 4]
# [7] pry(main)> array.to_a
# => [1, 2, 3, 4]
# [1] pry(main)> only_one = NonEmptyArray.new(1, [])
# => #<NonEmptyArray:0x00007fcb6db75b20 @first=1, @rest=[]>
# [2] pry(main)> only_one.first
# => 1
# [3] pry(main)> only_one.last
# => 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment