首页 > 解决方案 > 将函数传递到类和数组中

问题描述

这是我想通过将重复代码放在另一个函数中并将变量存储到另一个函数来利用重复代码的代码。我对这种功能类型并不是很新,所以我真的需要一些帮助,非常感谢你帮助我。

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

标签: rubyfunction

解决方案


这是我的代码是好还是太草率

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)

推荐阅读