解答例

課題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

課題11

root@c65985cfc603:/home/school# rails generate model Course name:string credit:integer compulsory:boolean
      invoke  active_record
      create    db/migrate/20221201155632_create_courses.rb
      create    app/models/course.rb
      invoke    test_unit
      create      test/models/course_test.rb
      create      test/fixtures/courses.yml
root@c65985cfc603:/home/school# rails db:migrate
== 20221201155632 CreateCourses: migrating ====================================
-- create_table(:courses)
   -> 0.0117s
== 20221201155632 CreateCourses: migrated (0.0117s) ===========================

root@c65985cfc603:/home/school# rails console
Loading development environment (Rails 7.0.4)
irb(main):001:0> x = Course.new(name: '体育1', credit: 1, compulsory: true)
=> #<Course:0x0000ffff7b4d9088 id: nil, name: "体育1", credit: 1, compulsory: true, created_at: nil, updated_at: nil>
irb(main):002:0> x.save
  TRANSACTION (0.2ms)  begin transaction
  Course Create (28.7ms)  INSERT INTO "courses" ("name", "credit", "compulsory", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?)  [["name", "体育1"], ["credit", 1], ["compulsory", 1], ["created_at", "2022-12-01 15:57:46.757863"], ["updated_at", "2022-12-01 15:57:46.757863"]]
  TRANSACTION (14.6ms)  commit transaction
=> true
irb(main):003:0> x = Course.new(name: 'プログラミング言語論', credit: 2, compulsory: false)
=> #<Course:0x0000ffff7b6787b8 id: nil, name: "プログラミング言語論", credit: 2, compulsory: false, created_at: nil,...
irb(main):004:0> x.save
  TRANSACTION (0.1ms)  begin transaction
  Course Create (41.2ms)  INSERT INTO "courses" ("name", "credit", "compulsory", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?)  [["name", "プログラミング言語論"], ["credit", 2], ["compulsory", 0], ["created_at", "2022-12-01 15:58:40.904291"], ["updated_at", "2022-12-01 15:58:40.904291"]]
  TRANSACTION (12.4ms)  commit transaction
=> true

課題12

root@c65985cfc603:/home/school# rails console
Loading development environment (Rails 7.0.4)
irb(main):001:0> x = Faculty.new(name: '環境情報')
=> #<Faculty:0x0000ffffae76c4c0 id: nil, name: "環境情報", created_at: nil, updated_at: nil>
irb(main):002:0> x.save
  TRANSACTION (0.2ms)  begin transaction
  Faculty Create (31.1ms)  INSERT INTO "faculties" ("name", "created_at", "updated_at") VALUES (?, ?, ?)  [["name", "環境情報"], ["created_at", "2022-12-01 16:05:32.549627"], ["updated_at", "2022-12-01 16:05:32.549627"]]
  TRANSACTION (13.5ms)  commit transaction
=> true
irb(main):003:0> y = Student.new(name: '花子', faculty_id: x.id, grade: 1)
=> #<Student:0x0000ffffae15d778 id: nil, name: "花子", faculty_id: 2, grade: 1, created_at: nil, updated_at: nil>
irb(main):004:0> y.save
  TRANSACTION (0.0ms)  begin transaction
  Faculty Load (1.8ms)  SELECT "faculties".* FROM "faculties" WHERE "faculties"."id" = ? LIMIT ?  [["id", 2], ["LIMIT", 1]]
  Student Create (13.4ms)  INSERT INTO "students" ("name", "faculty_id", "grade", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?)  [["name", "花子"], ["faculty_id", 2], ["grade", 1], ["created_at", "2022-12-01 16:05:54.003327"], ["updated_at", "2022-12-01 16:05:54.003327"]]
  TRANSACTION (7.4ms)  commit transaction
=> true
irb(main):005:0> y = Student.new(name: '一郎', faculty_id: x.id, grade: 2)
=> #<Student:0x0000ffffae1f5d48 id: nil, name: "一郎", faculty_id: 2, grade: 2, created_at: nil, updated_at: nil>
irb(main):006:0> y.save
  TRANSACTION (0.3ms)  begin transaction
  Faculty Load (17.3ms)  SELECT "faculties".* FROM "faculties" WHERE "faculties"."id" = ? LIMIT ?  [["id", 2], ["LIMIT", 1]]
  Student Create (22.4ms)  INSERT INTO "students" ("name", "faculty_id", "grade", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?)  [["name", "一郎"], ["faculty_id", 2], ["grade", 2], ["created_at", "2022-12-01 16:06:15.842145"], ["updated_at", "2022-12-01 16:06:15.842145"]]
  TRANSACTION (12.0ms)  commit transaction
=> true
irb(main):007:0> x.students
  Student Load (12.5ms)  SELECT "students".* FROM "students" WHERE "students"."faculty_id" = ?  [["faculty_id", 2]]
=>
[#<Student:0x0000ffffae248570
  id: 2,
  name: "花子",
  faculty_id: 2,
  grade: 1,
  created_at: Thu, 01 Dec 2022 16:05:54.003327000 UTC +00:00,
  updated_at: Thu, 01 Dec 2022 16:05:54.003327000 UTC +00:00>,
 #<Student:0x0000ffffae24feb0
  id: 3,
  name: "一郎",
  faculty_id: 2,
  grade: 2,
  created_at: Thu, 01 Dec 2022 16:06:15.842145000 UTC +00:00,
  updated_at: Thu, 01 Dec 2022 16:06:15.842145000 UTC +00:00>]

課題13

<!DOCTYPE html>
<html>
  <head>
    <title>School</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
    <%= javascript_importmap_tags %>
  </head>

  <body>
    <%= yield %>
    <br><%= image_tag "http://www.sfc.keio.ac.jp/img/logo.png", width: 300 %>
  </body>
</html>

課題14

<div id="<%= dom_id student %>">
  <p>
    <strong>Name:</strong>
    <%= student.name %>
  </p>

  <p>
    <strong>Faculty:</strong>
    <%= student.faculty.name %>
  </p>

  <p>
    <strong>Grade:</strong>
    <%= student.grade %>
  </p>

</div>

課題15

  • app/controllers/faculties_controller.rb

    class FacultiesController < ApplicationController
      def show
        @faculty = Faculty.find(params[:id])
        @students = @faculty.students
      end
    end
    
  • app/views/faculties/show.html.erb

    <h1>Faculties#show</h1>
    <p><b><%= @faculty.name %></b></p>
    
    <table>
      <% @students.each do |student| %>
        <tr>
          <td><%= student.id %></td>
          <td><%= student.name %></td>
        </tr>
      <% end %>
    </table>
    

課題16

  • app/controllers/course_controller.rb

    class CoursesController < ApplicationController
      def index
        @courses = Course.all
      end
    
      def show
        @course = Course.find(params[:id])
      end
    end
    
  • app/views/courses/index.html.erb

    <h1>Courses#index</h1>
    
    <table>
      <% @courses.each do |course| %>
        <tr>
          <td><%= course.name %></td>
          <td><%= link_to '詳細', course_path(course) %></td>
        </tr>
      <% end %>
    </table>
    
  • app/views/courses/show.html.erb

    <h1>Courses#show</h1>
    
    <p>
      <strong>科目名:</strong>
      <%= @course.name %>
    </p>
    
    <p>
      <strong>単位数:</strong>
      <%= @course.credit %>
    </p>
    
    <p>
      <% if @course.compulsory %>
        <strong>必修科目</strong>
      <% else %>
        <strong>選択科目</strong>
      <% end %>
    </p>
    
    <%= link_to 'Back', courses_path %>
    
  • config/routes.rb

    Rails.application.routes.draw do
      resources :courses, only: [ :index, :show ]
      resources :faculties, only: [ :show ]
      resources :students
    end
    

課題18

<%= form_with(model: student) do |form| %>
  <% if student.errors.any? %>
    <div style="color: red">
      <h2><%= pluralize(student.errors.count, "error") %> prohibited this student from being saved:</h2>

      <ul>
        <% student.errors.each do |error| %>
          <li><%= error.full_message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <div>
    <%= form.label :name, style: "display: block" %>
    <%= form.text_field :name %>
  </div>

  <div>
    <%= form.label :faculty, style: "display: block" %>
    <%= form.collection_select :faculty_id, Faculty.all, :id, :name %>
  </div>

  <div>
    <%= form.label :grade, style: "display: block" %>
    <% for i in 1..4 %>
      <%= form.radio_button :grade, i %>
      <%= form.label :grade, "#{i}年", value: i %>
    <% end %>
  </div>

  <div>
    <%= form.submit %>
  </div>
<% end %>