Avatar of paulfioravanti

paulfioravanti's solution

to Food Chain in the Ruby Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

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 Ruby resources 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
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
# frozen_string_literal: true

module FoodChain
  ANIMALS = %w[fly spider bird cat dog goat cow horse].freeze
  private_constant :ANIMALS
  WRIGGLED_AND_JIGGLED_AND_TICKLED_INSIDE_HER =
    "wriggled and jiggled and tickled inside her."
  private_constant :WRIGGLED_AND_JIGGLED_AND_TICKLED_INSIDE_HER
  COMMENTARY_ON_SWALLOWING_ANIMAL = Hash[
    ANIMALS.zip(
      [
        nil,
        "It #{WRIGGLED_AND_JIGGLED_AND_TICKLED_INSIDE_HER}",
        "How absurd to swallow a bird!",
        "Imagine that, to swallow a cat!",
        "What a hog, to swallow a dog!",
        "Just opened her throat and swallowed a goat!",
        "I don't know how she swallowed a cow!",
        nil
      ]
    )
  ].freeze
  private_constant :COMMENTARY_ON_SWALLOWING_ANIMAL
  FOLLOW_UP_FOR_SWALLOWING_ANIMAL = lambda do |animal|
    if animal == "horse"
      "She's dead, of course!"
    else
      FOLLOW_UP_ACTION_STACK[STACK_HEIGHT[animal]..-1].join("\n")
    end
  end
  private_constant :FOLLOW_UP_FOR_SWALLOWING_ANIMAL
  VERSES_FOR = lambda do |animal|
    [
      "I know an old lady who swallowed a #{animal}.",
      COMMENTARY_ON_SWALLOWING_ANIMAL[animal],
      FOLLOW_UP_FOR_SWALLOWING_ANIMAL[animal]
    ].compact.join("\n")
  end
  private_constant :VERSES_FOR
  SHE_SWALLOWED_THE = lambda do |animal, phrase|
    "She swallowed the #{animal} #{phrase}"
  end
  private_constant :SHE_SWALLOWED_THE
  TO_CATCH_THE = lambda do |animal|
    to_catch = "to catch the #{animal}"
    if animal == "spider"
      "#{to_catch} that #{WRIGGLED_AND_JIGGLED_AND_TICKLED_INSIDE_HER}"
    else
      "#{to_catch}."
    end
  end
  private_constant :TO_CATCH_THE
  STACK_HEIGHT = Hash[ANIMALS[0..-2].reverse.zip((-7..-1))].freeze
  private_constant :STACK_HEIGHT
  FOLLOW_UP_ACTION_STACK = [].tap do |array|
    ANIMALS[0..-2].reverse.each_cons(2) do |animal, other_animal|
      array << SHE_SWALLOWED_THE[animal, TO_CATCH_THE[other_animal]]
    end
    array << "I don't know why she swallowed the fly. Perhaps she'll die.\n"
  end.freeze
  private_constant :FOLLOW_UP_ACTION_STACK

  module_function

  def song
    ANIMALS.map { |animal| VERSES_FOR[animal] }.join("\n") + "\n"
  end
end

Community comments

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

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?