解答例¶
課題1
n = gets.to_i for i in 0..n-1 (n-i).times do print " " end (i*2+1).times do print "*" end puts end課題2
def myprime (n) i = 2 until i*i > n return false if n%i == 0 i += 1 end return true end puts (if myprime gets.to_i then "yes" else "no" end)課題3
def myprime (n) raise RuntimeError if n < 2 i = 2 until i*i > n return false if n%i == 0 i += 1 end return true end print "2以上の整数を入れてください:" begin puts (if myprime gets.to_i then "yes" else "no" end) rescue RuntimeError print "2以上の整数だと言ってるでしょうが!:" retry end課題4
x = [] loop do print '数値? ' a = gets.to_i break if a == 0 x.push(a) end while x.length > 0 do puts x.pop end課題5
dictionary = { 'dog' => '犬', 'cat' => '猫' } loop do print '英語:' x = gets.chomp if dictionary[x] puts "日本語:#{dictionary[x]}" else print "#{x}の日本語訳を教えてください:" y = gets.chomp dictionary[x] = y end end課題6
longest = '' IO.foreach('words.txt') do |line| if longest.length < line.length longest = line end end puts longest課題7
def arraycalc(x, y) result = [] while x.length > 0 result << (yield x.shift, y.shift) end result end課題8
class Account attr_reader :balance def initialize @balance = 0 end def deposit(n) @balance += n end def withdraw(n) if @balance >= n @balance -= n true # 引き出し成功 else puts "残高不足です。" false # 引き出し失敗 end end def transfer(x, n) if withdraw(n) # 自分の口座から引き出せれば x.deposit(n) # 相手の口座に入金する end end end課題9
class Student # 同じ名前のクラス宣言は、追加されていく def affiliation university + faculty end end