Skip to content

Instantly share code, notes, and snippets.

@JoelQ
Created August 9, 2018 17:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoelQ/8cd5a1a5a0f4371edc94fd43eef0116a to your computer and use it in GitHub Desktop.
Save JoelQ/8cd5a1a5a0f4371edc94fd43eef0116a to your computer and use it in GitHub Desktop.
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