Skip to content

Instantly share code, notes, and snippets.

@ChrisDrit
Created July 12, 2017 18:16
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 ChrisDrit/a66965ab100314a7f5d4d2bd9bdd0c20 to your computer and use it in GitHub Desktop.
Save ChrisDrit/a66965ab100314a7f5d4d2bd9bdd0c20 to your computer and use it in GitHub Desktop.
Citrusbyte Code Example from Chris Dritsas
# ----------------------
# Chris Dritsas
# Code Example
# ----------------------
# return flattened array
def squash(data=[])
# validate
raise "argument must be a non-empty array" if data.empty? or !data.is_a? Array
# instantiate and return an array object
data.each_with_object([]) do |item, squashed|
# use recursion to break out sub-array's
element = (item.is_a? Array) ? squash(item) : item
# use the splat operator '*' to break down array
# ruby-doc.org/core-2.3.0/doc/syntax/calling_methods_rdoc.html#label-Array+to+Arguments+Conversion
squashed.push *(element)
end
end
# rspec
describe "#squash" do
context "fails" do
it "passing a string" do
expect{ squash("some data") }.to raise_error()
end
it "passing an empty array" do
expect{ squash([]) }.to raise_error()
end
end
context "succeeds" do
it "passing an array of integers" do
expect( squash([1,2,3]) ).to eq([1,2,3])
end
it "passing an array of integers with sub-array's" do
expect( squash([[1,2,[3]],4]) ).to eq([1,2,3,4])
end
it "passing an array of strings with sub-array's" do
expect( squash([["hi", "bye", ["foo"]], "bar"]) ).to eq(["hi", "bye", "foo", "bar"])
end
it "passing a mixed array with sub-array's" do
expect( squash([[1, 2, 3, ["foo", ["bar"]]]]) ).to eq([1, 2, 3, "foo", "bar"])
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment