ruby - 将函数传递到类和数组中
问题描述
这是我想通过将重复代码放在另一个函数中并将变量存储到另一个函数来利用重复代码的代码。我对这种功能类型并不是很新,所以我真的需要一些帮助,非常感谢你帮助我。
def main
marks = 0
puts "1. What does the == operator do?"
puts "(a) calculates an arithmetic solution."
puts "(c) checks for e"
puts "Your answer: "
begin
answer = gets.chomp
end while (answer != 'a' && answer != 'b' && answer != 'c' && answer != 'd')
if answer == 'c'
score += 1
puts "Correct "
else
puts "Wrong "
end
puts "2. Which is NOT a C keyword?"
puts "(a) when"
puts "(b) const"
puts "(c) unsigned"
puts "Your answer: "
begin
answer = gets.chomp
end while (answer != 'a' && answer != 'b' && answer != 'c' && answer != 'd')
if answer == 'a'
score += 1
puts "Correct "
else
puts "Wrong "
end
puts "3. In function call, the actual parameters are separated by"
puts "(a) semicolons"
puts "(b) colons"
puts "(c) commas"
puts "Your answer: "
note
answer = gets.chomp
if answer != 'a' && answer != 'b' && answer != 'c' && answer != 'd'
if answer == 'c'
score += 1
puts "Correct "
else
puts "Wrong "
end
end
main
解决方案
这是我的代码是好还是太草率
class Question
attr_accessor :prompt, :answer
def initialize(prompt, answer)
@prompt = prompt
@answer = answer
end
end
p1 =
"1. What does the == operator do?\n
(c) checks for equality\n
(d) draws the '=' character\n
Your answer: \n"
p2 =
"1. What does the == operator do?\n
(b) assigns a value to a variable.\n
(c) checks for equality\n
(d) draws the '=' character\n
Your answer: "
p3 =
"3. the actual parameters are separated by\n
(b) colons\n
(c) commas\n
Your answer: "
questions = [
Question.new(p1, "c"),
Question.new(p2, "a"),
Question.new(p3, "c"),
]
def run_test(questions)
answer = ""
score = 0
for question in questions
puts question.prompt
answer = gets.chomp
(answer != 'a' && answer != 'b' && answer != 'c' && answer != 'd')
if answer == question.answer
score += 1
puts "Correct " =
else
puts "Wrong "
end
end
end
run(questions)
推荐阅读
- terraform - 无法将标签添加到中转网关默认路由表
- python - Wagtail CMS 通过 API 请求发送图像 URL
- android - Android底页上的静态页脚视图
- c# - 使用 DateTime.TryParseExact C#
- tensorflow - 如何使用 Tensorflow 对象检测 API 启用多 GPU 训练
- javascript - 重置选项列表字段
- python-3.x - Python从两个具有相同长度的列表中获取唯一值和最小值对
- processing - 在处理 3 问题中将摩尔斯电码编码器转换为解码器
- reactjs - Material UI Select 组件上的“keepMounted”属性未将菜单项安装到 DOM
- python - 无法使用 BeautifulSoup 和 Requests 抓取下拉菜单