<commit_before><commit_msg>Exercise 41: Learning To Speak Object Oriented<commit_after>require 'open-uri'

WORD_URL = "http://learncodethehardway.org/words.txt"
WORDS = []

PHRASES = {
  "class ### < ###\nend" => "Make a class named ### that is-a ###.",
  "class ###\n\tdef initialize(@@@)\n\tend\nend"  => "class ### has-a initialize that takes @@@ parameters.",
  "class ###\n\tdef ***(@@@)\n\tend\nend" => "class ### has-a function named *** that takes @@@ parameters.",
  "*** = ###.new()"  => "Set *** to an instance of class ###.",
  "***.***(@@@)"  => "From *** get the *** function, and call it with parameters @@@.",
  "***.*** = '***'" => "From *** get the *** attribute and set it to '***'."
}

PHRASE_FIRST = ARGV[0] == "english"

open(WORD_URL) {|f|
  f.each_line {|word| WORDS.push(word.chomp)}
}

def craft_names(rand_words, snippet, pattern, caps=false)
  names = snippet.scan(pattern).map do
    word = rand_words.pop()
    caps ? word.capitalize : word
  end
  
  return names*2
end

def craft_params(rand_words, snippet, pattern, caps=false)
  names = (0...snippet.scan(pattern).length).map do
    param_count = rand(3)+1
    params = (0...param_count).map {|x| rand_words.pop()}
    params.join(', ')
  end

  return names * 2
end

def convert(snippet, phrase)
  rand_words = WORDS.sort_by {rand}
  class_names = craft_names( rand_words, snippet, /###/, caps=true)
  other_names = craft_names( rand_words, snippet, /\*\*\*/)
  param_names = craft_params( rand_words, snippet, /@@@/)

  results = []

  for sentence in [snippet, phrase]
    #fake class names, also coies sentence
    result = sentence.gsub(/###/){|x| class_names.pop}
    result.gsub!(/\*\*\*/){|x| other_names.pop}
    result.gsub!(/@@@/) {|x| param_names.pop}

    results.push(result)
  end
  return results
end

# keep going until they CTRL-D
loop do
  snippets = PHRASES.keys().sort_by{rand}
  
  for snippet in snippets
    phrase = PHRASES[snippet]
    question, answer = convert(snippet, phrase)
    
    if PHRASE_FIRST
      question, answer = answer,question
    end

    print question, "\n\n "

    exit(0) unless STDIN.gets

    puts "\nANSWER: %s\n\n" % answer
  end
end

{'fraction_non_alphanumeric': 0.18968692449355432, 'fraction_numerical': 0.004604051565377533, 'mean_word_length': 3.4528688524590163, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5050423', 'n_tokens_mistral': 805, 'n_tokens_neox': 786, 'n_words': 189}