21、编写一个程序,允许你输入诸如“feed”和“walk”之类的命令,并在你的小龙对象上调用这些方法。
以下是实现该功能的程序代码:
puts "What would you like to name your baby dragon?"
name = gets.chomp
dragon = Dragon.new(name)
while true
puts
puts "commands: feed, toss, walk, rock, put_to_bed, exit"
command = gets.chomp
if command == "exit"
break
elsif dragon.respond_to?(command) && !Object.new.respond_to?(command)
dragon.send(command)
else
puts "Huh? Please type one of the commands."
end
end
此代码先让用户为小龙命名,接着进入一个循环,提示用户输入命令,根据用户输入调用小龙对象对应的方法,输入“ exit
”则退出程序。同时,代码会检查输入的命令是否为小龙对象特有的方法,若不是则提示用户重新输入。
22、使用开放问答数据库的 API 获取问答问题,然后向用户提问。统计用户答对的数量,并在最后告知用户的答题情况。(确保你不会忽略 API 返回的响应代码。)
以下是一个 Ruby 代码示例来实现这个功能:
require "net/http"
require "json"
# 可轻松调整问题数量
num_questions = 1
url = URI("https://opentdb.com/api.php?amount=#{num_questions}")
response = JSON.parse(Net::HTTP.get(url))
# 检查响应代码
if response["response_code"] != 0
puts "从服务器获取问题失败。"
puts "(响应代码: #{response["response_code"]})"
exit
end
def ask_for_choice(answers)
idx = 1
answers.each do |a|
puts "#{idx}. #{a}"
idx = idx + 1
end
while true
choice = gets.chomp.to_i
if (choice >= 1 && choice <= answers.length)
return choice
else