Skip to content

Instantly share code, notes, and snippets.

@roktas
Last active March 10, 2016 11:44
Show Gist options
  • Save roktas/ad15d355b4542480583e to your computer and use it in GitHub Desktop.
Save roktas/ad15d355b4542480583e to your computer and use it in GitHub Desktop.
Test üreteci
#!/usr/bin/env ruby
require 'yaml'
require 'forwardable'
module MultipleChoice
module Choice
CHOICES = (:a..:e).to_a
refine Symbol do
INDEX = CHOICES.zip((0...CHOICES.size).to_a)
def to_index
INDEX[self]
end
def sanitize
fail TypeError, "'#{self}' is not a valid choice" unless INDEX.key? self
self
end
end
refine Fixnum do
def to_choice
CHOICES[self]
end
def sanitize
return self if self > 0 && self < CHOICES.size
fail TypeError, "'#{self}' is out of range to become a valid choice"
end
end
refine Array do
def to_choices
return Hash[CHOICES.zip self] if size == CHOICES.size
fail TypeError, 'size mismatch in choice list'
end
end
def self.choices
CHOICES
end
def self.size
CHOICES.size
end
end
class Answers
using Choice
include Choice
attr_reader :correct
def initialize(answers, correct = nil)
@answers = answers.to_choices
@correct = correct ? correct.to_choice.sanitize : :a
end
def shuffle!
@answers = Hash[@answers.to_a.shuffle]
@correct = @answers.keys.index(@correct).to_choice
end
def to_s
@answers.values.each_with_index.map do |c, i|
"#{i.to_choice}. #{c}"
end.join("\n")
end
end
class Item
extend Forwardable
def_delegators :@answers, :shuffle!, :correct
attr_reader :question, :answers
def initialize(question, answers, correct = nil)
@question = question
@answers = Answers.new(answers, correct)
end
def to_s
"#{question}\n#{answers}"
end
end
class Exam
extend Forwardable
def_delegators :@items, :each, :each_with_index, :map, :size, :[], :<<
attr_reader :items
def initialize(items)
@items = items
end
def shuffle!
@items.shuffle!
each(&:shuffle!)
end
def to_s
each_with_index.map do |item, i|
"#{i + 1}. #{item}"
end.join("\n\n")
end
def corrects
map(&:correct)
end
def self.from_yaml(string)
new(
YAML.load(string).map do |item|
Item.new item['question'], item['answers'], item['correct']
end
)
end
end
end
if __FILE__ == $PROGRAM_NAME
def main
include MultipleChoice
e = Exam.from_yaml DATA
e.shuffle!
puts 'Exam'
puts
puts e
puts
puts 'Corrects'
puts
puts e.corrects
end
main
end
__END__
- question: |
Ekranda ne görüntülenir?
~~~
class Foo
attr_accessor :a
def initialize(a)
@a = a
end
def bar
a = 13
end
end
f = Foo.new 19
f.bar
puts f.a
~~~
answers:
- 19
- 13
- nil
- 0
- Hiçbiri
- question: |
Ruby'de nesne metodu gövdelerinde `@` ile başlayan bir tanımlayıcı
answers:
- Nesne niteliğidir
- Yerel değişkendir
- Genel (global) değişkendir
- Sınıf değişkenidir
- Hiçbiri
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment