Подсказка Ruby TTY undefined переменная или метод

Итак, для задания я создаю простую игру в жанре «выберите свой собственный приключенческий терминал».

У меня есть неопределенная локальная переменная или ошибка метода, которую я не могу исправить.

prompt.select("Do you stop to listen? Do you leave the path to investigate? or do you spur your horse on faster?") do |menu|
    menu.choice "Stop to listen", -> {paragraph_4}
    menu.choice "Leave path and investigate", -> {paragraph_5}
    menu.choice "Spur horse on faster", -> {paragraph_7}
  
  end 
There are three paragraphs stored in each of the 4 ruby files-

prompt = TTY::Prompt.new

$paragraph_4 = def paragraph_4

prompt = TTY::Prompt.new

puts ""
puts "" 
puts "   Stopping to listen it seems whatever is moving in the brush is doing the same. Your horse stamps a foot impatiently."

prompt.select("Will you dismount? Do you call out? or do you continue on your way?") do |menu|
  menu.choice "Dismount", -> {paragraph_7}
  menu.choice "Call out", -> {paragraph_8}
  menu.choice "Continue", -> {paragraph_7}

end

$paragraph_5 = def paragraph_5
uts ""
puts "" 
puts ""
puts "  Suddenly a giant spider leaps from the brush and burys its huge fangs in your neck."
puts "" 
puts "  YOU HAVE DIED

Это работает только для первого абзаца каждого файла. Как если бы я сделал первый выбор в подсказке, он работает, но второй или третий -

game.rb: 77: in block (2 levels) in <main>': undefined local variable or method paragraph_2 'для основного: Object (NameError)

Я не понимаю почему?

prompt = TTY::Prompt.new

$paragraph_1 = def paragraph_1 

prompt = TTY::Prompt.new

   puts ""
   puts ""
   puts "  'Ah the north road, a wise choice friend as your way will meander towards Ered Mithrin and Durins folk of the Grey Mountains'
  'Perhaps like Gandalf and his companions who whence this way you will find Erebor the lonely mountain, whereby Smaug the Terrible met his end.'
  'Now friend the hour grows late and you best away lest you not find a clearing within the woods to light a fire for camp at night.
  'Bidding the kind old man well and flicking a silver coin his way you nudge your horse with your knees and head towards the woods.'
  'As you approach the branchs of the dark and twisted trees seem to reach out and their trunks rear up and lean forward to engulf you. Soon the space'
  'between the boughs becomes thinner and thinner and although what seemed like moments ago late afternoon now seems like a twighlight under the weight of the ancient forest."

  "As you walk deeper into the dark woods you hear a rustling and from the corner of your eye you see movement to your left"

  prompt.select("Do you stop to listen? Do you leave the path to investigate? or do you spur your horse on faster?") do |menu|
    menu.choice "Stop to listen", -> {paragraph_4}
    menu.choice "Leave path and investigate", -> {paragraph_5}
    menu.choice "Spur horse on faster", -> {paragraph_7}

  end 


  
  $paragraph_2 = def paragraph_2 

  prompt = TTY::Prompt.new

  puts ""
  puts ""
  puts "  'Ah the middle way, a sensible choice friend as your way will take you through the lands of the Sindarin or Silvan Elves and Thranduil's realm'
  'Now friend the hour grows late and you best away lest you not find a clearing within the woods to light a fire for camp at night.
  'Bidding the kind old man well and flicking a silver coin his way you nudge your horse with your knees and head towards the woods.'
  'As you approach the branchs of the dark and twisted trees seem to reach out and their trunks rear up and lean forward to engulf you. Soon the space'
  'between the boughs becomes thinner and thinner and although what seemed like moments ago late afternoon now seems like a twighlight under the weight of the ancient forest."
  ""
  "As you walk deeper into the dark woods you hear a rustling and from the corner of your eye you see movement to your left"

  prompt.select("Do you stop to listen? Do you leave the path to investigate? or do you spur your horse on faster?") do |menu|
    menu.choice "Stop to listen", -> {paragraph_4}
    menu.choice "Leave path and investigate", -> {paragraph_5}
    menu.choice "Spur horse on faster", -> {paragraph_7}
  
  end 


person Luke Patch    schedule 02.06.2021    source источник
comment
Лямбды - это замыкания. Где определен метод # paragraph_2?   -  person Todd A. Jacobs    schedule 02.06.2021
comment
Я добавил еще один фрагмент кода, если бы вы могли взглянуть, Тодд будет признателен.   -  person Luke Patch    schedule 03.06.2021
comment
Вы вызываете методы внутри лямбда-выражений. Методы выходят за рамки.   -  person Todd A. Jacobs    schedule 03.06.2021
comment
Вы также назначаете методы глобальным переменным, но они не являются лямбдами, и вы никогда не пытаетесь их вызывать. Непонятно, почему вы думаете, что это сработает, и ваши примеры на самом деле недостаточно объясняют ваш мыслительный процесс, чтобы помочь в дальнейшем.   -  person Todd A. Jacobs    schedule 03.06.2021
comment
Я новичок в Ruby и изучаю кодирование всего 3 месяца, так что простите за мое незнание. Что я хочу сделать, так это отойти от каждого абзаца через подсказку tty, а затем снова до конца истории. Если бы вы могли посоветовать, как это будет работать, это было бы полезно.   -  person Luke Patch    schedule 03.06.2021


Ответы (1)


Вот пример того, что вы хотите сделать:

require 'tty-prompt'

class MyGame
  attr_accessor :prompt

  def initialize
    @prompt = TTY::Prompt.new
  end

  def paragraph_1
    prompt.select("What do you do?") do |menu|
      menu.choice "Stop to listen",->{paragraph_2}
      menu.choice "Leave path and investigate",->{paragraph_3}
      menu.choice "Spur horse on faster",->{paragraph_4}
    end
  end

  def paragraph_2
    # TODO: implement choices; use paragraph_1 as an example
    prompt.select('Paragraph 2') do |menu|
      menu.choice 'P2 Choice 1'
      menu.choice 'P2 Choice 2'
      menu.choice 'P2 Choice 3'
    end
  end

  def paragraph_3
    # TODO: implement choices; use paragraph_1 as an example
    prompt.select('Paragraph 3') do |menu|
      menu.choice 'P3 Choice 1'
      menu.choice 'P3 Choice 2'
      menu.choice 'P3 Choice 3'
    end
  end

  def paragraph_4
    # TODO: implement choices; use paragraph_1 as an example
    prompt.select('Paragraph 4') do |menu|
      menu.choice 'P4 Choice 1'
      menu.choice 'P4 Choice 2'
      menu.choice 'P4 Choice 3'
    end
  end
end

my_game = MyGame.new
my_game.paragraph_1

Я не предлагаю определять ваши методы в $ глобальных переменных. Классы / модули - лучший способ организовать ваш код.

Кроме того, я бы предложил лучшую схему именования. Например:

  • cool_path1
  • cool_path1_choice1
  • cool_path1_choice2
  • cool_path1_choice3

Или что-то подобное. Вы можете разбить это на еще больше классов / модулей в разные файлы, если хотите.

Я вижу, что это тоже становится довольно сложным. Внутри вы можете сохранить некоторый тип состояния (какой выбор сделал наш герой) и принимать решения оттуда.

Не бойтесь просить своего учителя о помощи. Это одна из целей учителей. Может быть, ваш учитель поможет вам с кодом и / или дизайном.

person esotericpig    schedule 03.06.2021