Ruby编程实践:从交互到排序算法

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值