Skip to content

Instantly share code, notes, and snippets.

@armw4
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save armw4/8842332 to your computer and use it in GitHub Desktop.
Save armw4/8842332 to your computer and use it in GitHub Desktop.
A bit of syntactic sugar the Array contructor exposes to create a fixed number of instances.

by Antwan Wimberly

I was not aware this was possible until I came across this post looking for examples of using ActiveRecord and rspec in unison.

I frequently make use of sample data in my posts; most commonly in the form of arrays.

In the midst of "shooting the breeze" with my fellow companions on the awesome "programmer files" gist, I could have made use of:

Array.new(3) { Person.new }

That's a pretty convenient bit of syntax to call upon moving forward. It's essentially writing the loop for you underneath the covers; repeatedly invoking the block. I'm willing to bet you I could reverse engineer this guy too; let me take a stab at it.

Before I hack on this sample, I'll fill you in on my thought process. Declaratively speaking, "Invoke this block n number of times."

That's essentially the specification we want to adhere to. "Let's dance, shall we?".

require 'rspec/autorun'

module Kernel
  def AntwanArray(count, &block)
  end
end

describe 'AntwanArray' do
  let(:count) { 3 }

  it 'should create an array with the number of elements equal to count' do
    expect(AntwanArray(count) { Array(5) } ).to eq Array.new(count) { Array(5) }
  end
end

And upon running our spec, we get:

Failures:

  1) AntwanArray should create an array with the number of elements equal to count
     Failure/Error: Unable to find matching line from backtrace

       expected: [[5], [5], [5]]
            got: nil

       (compared using ==)
     # array-conversion.rb:15:in `block (2 levels) in <main>'

Finished in 0.00137 seconds
1 example, 1 failure

Failed examples:

rspec array-conversion.rb:12 # AntwanArray should create an array with the number of
elements equal to count

shell returned 1

"It's time to pass the test"

module Kernel
  def AntwanArray(count, &block)
    result = []

    count.times { result << yield }

    result
  end
end
Finished in 0.00162 seconds
1 example, 0 failures

Press ENTER or type command to continue

"All green now"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment