学习Ruby艰难的方式#41

时间:2014-03-04 11:01:52

标签: ruby variables hash

嗨,我正在向LRtHW学习,我被卡住了......

我有这样的程序:

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) do |f| 
  f.each_line {|word| WORDS.push(word.chomp)}
end

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)
  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 name, also copies sentence
    result = sentence.gsub(/###/) {|x| class_names.pop}
    #fake other names
    result.gsub!(/\*\*\*/) {|x| other_names.pop}
    #fake parameter list
    result.gsub!(/@@@/) {|x| param_names.pop}
    results.push(result)
  end

  return results
end

# keep going until they hit 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> "
    odp = gets.chomp

    if odp == "exit"
      exit(0)
    end

    #exit(0) unless STDIN.gets
    puts "\nANSWER: %s\n\n" % answer
  end
end  

我理解大部分代码,但我遇到了问题:

for sentence in [snippet, phrase]

我知道它是一个“for”循环并且它创建了一个“句子”变量,但是循环如何知道它需要查看散列的键和值“PHRASES”

我的第二个“墙”是:

question, answer = convert(snippet, phrase)

看起来它创建并分配“问题”和“用”片段“和”短语“参数为”转换“方法回答变量...再次如何将”问题“分配给键并回答价值。

我知道这可能很简单但是现在它阻止了我的想法:(

1 个答案:

答案 0 :(得分:1)

关于for循环的第一个问题:

查看for循环的定义位置。它在convert()方法中,对吗?并且convert()方法传递两个参数:一个snippet和一个phrase。所以循环不是“寻找”PHRASES哈希中的值,是提供它的那个。你正在使用方法的参数。

关于作业的第二个问题:

在Ruby中,我们可以做一些叫做“解构赋值”的事情。这意味着我们可以为多个变量分配一个数组,每个变量将在数组中保存一个值。这就是你的计划中发生的事情。 convert()方法返回一个两项数组,并为数组中的每个项提供一个名称(问题和答案)。

这是解构分配的另一个例子:

a, b, c = [1, 2, 3]
a # => returns 1
b # => returns 2
c # returns 3

在IRB中尝试一下,看看你是否掌握了它。如果我能帮助澄清任何事情,或者我是否误解了你的问题,请告诉我。问“简单”问题你永远不会感到难过!