Avatar of davearonson

davearonson's solution

to Food Chain in the Ruby Track

Published at Jul 13 2018 · 1 comment
Instructions
Test suite
Solution

Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

Generate the lyrics of the song 'I Know an Old Lady Who Swallowed a Fly'.

While you could copy/paste the lyrics, or read them from a file, this problem is much more interesting if you approach it algorithmically.

This is a cumulative song of unknown origin.

This is one of many common variants.

I know an old lady who swallowed a fly.
I don't know why she swallowed the fly. Perhaps she'll die.

I know an old lady who swallowed a spider.
It wriggled and jiggled and tickled inside her.
She swallowed the spider to catch the fly.
I don't know why she swallowed the fly. Perhaps she'll die.

I know an old lady who swallowed a bird.
How absurd to swallow a bird!
She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.
She swallowed the spider to catch the fly.
I don't know why she swallowed the fly. Perhaps she'll die.

I know an old lady who swallowed a cat.
Imagine that, to swallow a cat!
She swallowed the cat to catch the bird.
She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.
She swallowed the spider to catch the fly.
I don't know why she swallowed the fly. Perhaps she'll die.

I know an old lady who swallowed a dog.
What a hog, to swallow a dog!
She swallowed the dog to catch the cat.
She swallowed the cat to catch the bird.
She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.
She swallowed the spider to catch the fly.
I don't know why she swallowed the fly. Perhaps she'll die.

I know an old lady who swallowed a goat.
Just opened her throat and swallowed a goat!
She swallowed the goat to catch the dog.
She swallowed the dog to catch the cat.
She swallowed the cat to catch the bird.
She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.
She swallowed the spider to catch the fly.
I don't know why she swallowed the fly. Perhaps she'll die.

I know an old lady who swallowed a cow.
I don't know how she swallowed a cow!
She swallowed the cow to catch the goat.
She swallowed the goat to catch the dog.
She swallowed the dog to catch the cat.
She swallowed the cat to catch the bird.
She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.
She swallowed the spider to catch the fly.
I don't know why she swallowed the fly. Perhaps she'll die.

I know an old lady who swallowed a horse.
She's dead, of course!

For installation and learning resources, refer to the exercism help page.

For running the tests provided, you will need the Minitest gem. Open a terminal window and run the following command to install minitest:

gem install minitest

If you would like color output, you can require 'minitest/pride' in the test file, or note the alternative instruction, below, for running the test file.

Run the tests from the exercise directory using the following command:

ruby food_chain_test.rb

To include color from the command line:

ruby -r minitest/pride food_chain_test.rb

Source

Wikipedia http://en.wikipedia.org/wiki/There_Was_an_Old_Lady_Who_Swallowed_a_Fly

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

food_chain_test.rb

require 'minitest/autorun'

require_relative 'food_chain'

class NoCheating < IOError
  def message
    "The use of File.open and IO.read is restricted.\n"                \
    'This exercise intends to help you improve your ability to work ' \
    'with data generated from your code. Your program must not read ' \
    'the song.txt file.'
  end
end

class FoodChainTest < Minitest::Test
  # This test is an acceptance test.
  #
  # If you find it difficult to work the problem with so much
  # output, go ahead and add a `skip`, and write whatever
  # unit tests will help you. Then unskip it again
  # to make sure you got it right.
  # There's no need to submit the tests you write, unless you
  # specifically want feedback on them.
  def test_the_whole_song
    song_file = File.expand_path('../song.txt', __FILE__)
    expected  = IO.read(song_file)
    assert_equal expected, FoodChain.song
  end

  # Tests that an error is effectively raised when IO.read or
  # File.open are used within FoodChain.
  def test_read_guard
    song_file = File.expand_path('../song.txt', __FILE__)
    ["IO.read '#{song_file}'", "File.open '#{song_file}'"].each do |trigger|
      assert_raises(NoCheating) { FoodChain.send :class_eval, trigger }
    end
  end

  # Problems in exercism evolve over time,
  # as we find better ways to ask questions.
  # The version number refers to the version of the problem you solved,
  # not your solution.
  #
  # Define a constant named VERSION inside of BookKeeping.
  # If you are curious, read more about constants on RubyDoc:
  # http://ruby-doc.org/docs/ruby-doc-bundle/UsersGuide/rg/constants.html
  def test_version
    skip
    assert_equal 2, BookKeeping::VERSION
  end
end

module RestrictedClasses
  class File
    def self.open(*)
      fail NoCheating
    end

    def self.read(*)
      fail NoCheating
    end

    def open(*)
      fail NoCheating
    end

    def read(*)
      fail NoCheating
    end
  end

  class IO
    def self.read(*)
      fail NoCheating
    end

    def read(*)
      fail NoCheating
    end
  end
end

FoodChain.prepend RestrictedClasses
class Animal
  ATTRS = %i(name comment reason catch_extra)
  attr_accessor *ATTRS
  def initialize(options)
    options.each { |key, val| self.send("#{key}=".to_s, val) }
  end
end


class FoodChain

  VERSION = 2

  def self.song
    ANIMALS.map { |animal| stanza_for(animal) }.join("\n\n")
  end

  private

  ANIMALS = [
    Animal.new(name: "fly",
               # note no comment, but a special reason!
               reason: "I don't know why she swallowed the fly."\
                       " Perhaps she'll die."),
    Animal.new(name: "spider",
               comment:
                 "It wriggled and jiggled and tickled inside her.",
               # note another special item here:
               catch_extra:
                 " that wriggled and jiggled and tickled inside her"),
    Animal.new(name: "bird",
               comment: "How absurd to swallow a bird!"),
    Animal.new(name: "cat",
               comment: "Imagine that, to swallow a cat!"),
    Animal.new(name: "dog",
               comment: "What a hog, to swallow a dog!"),
    Animal.new(name: "goat",
               comment: "Just opened her throat and swallowed a goat!"),
    Animal.new(name: "cow",
               comment: "I don't know how she swallowed a cow!"),
    Animal.new(name: "horse",
               comment: "She's dead, of course!\n")
  ]

  def self.reason_line_for_animal(animal)
    animal.reason || begin
      prev = ANIMALS[ANIMALS.index(animal) - 1]
      "She swallowed the #{animal.name} to catch the #{prev.name}"\
        "#{prev.catch_extra}."
    end
  end

  def self.reason_lines_for_stanza(animal)
    return [] if animal == ANIMALS.last  # special case
    # could also do take_while not stanza_animal, and also push that
    ANIMALS[0, ANIMALS.index(animal) + 1].reverse.map { |a|
      reason_line_for_animal(a) }
  end

  def self.stanza_for(animal)
    # not worrying about "a" vs. "an"...
    (["I know an old lady who swallowed a #{animal.name}.",
       animal.comment].
       compact +
       reason_lines_for_stanza(animal)).join("\n")
  end

end

Community comments

Find this solution interesting? Ask the author a question to learn more.
Avatar of jmodjeska

This is ten million percent more readable than what I came up with. Nice job.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?