.. highlight:: ruby ****** 解答例 ****** .. _ex1-answer: .. admonition:: 課題1 :class: exercise :: 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 .. _ex2-answer: .. admonition:: 課題2 :class: exercise :: 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) .. _ex3-answer: .. admonition:: 課題3 :class: exercise :: 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 .. _ex4-answer: .. admonition:: 課題4 :class: exercise .. code-block:: ruby 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 .. _ex5-answer: .. admonition:: 課題5 :class: exercise .. code-block:: ruby 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 .. _ex6-answer: .. admonition:: 課題6 :class: exercise .. code-block:: ruby longest = '' IO.foreach('words.txt') do |line| if longest.length < line.length longest = line end end puts longest .. _ex7-answer: .. admonition:: 課題7 :class: exercise .. code-block:: ruby def arraycalc(x, y) result = [] while x.length > 0 result << (yield x.shift, y.shift) end result end .. _ex8-answer: .. admonition:: 課題8 :class: exercise .. code-block:: ruby 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 .. _ex9-answer: .. admonition:: 課題9 :class: exercise .. code-block:: ruby class Student # 同じ名前のクラス宣言は、追加されていく def affiliation university + faculty end end .. _ex11-answer: .. admonition:: 課題11 :class: exercise .. code-block:: irb 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) => # 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) => # 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 .. _ex12-answer: .. admonition:: 課題12 :class: exercise .. code-block:: irb root@c65985cfc603:/home/school# rails console Loading development environment (Rails 7.0.4) irb(main):001:0> x = Faculty.new(name: '環境情報') => # 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) => # 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) => # 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]] => [#, #] .. _ex13-answer: .. admonition:: 課題13 :class: exercise .. code-block:: erb School <%= csrf_meta_tags %> <%= csp_meta_tag %> <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %> <%= javascript_importmap_tags %> <%= yield %>
<%= image_tag "http://www.sfc.keio.ac.jp/img/logo.png", width: 300 %> .. _ex14-answer: .. admonition:: 課題14 :class: exercise .. code-block:: erb

Name: <%= student.name %>

Faculty: <%= student.faculty.name %>

Grade: <%= student.grade %>

.. _ex15-answer: .. admonition:: 課題15 :class: exercise * ``app/controllers/faculties_controller.rb`` .. code-block:: ruby class FacultiesController < ApplicationController def show @faculty = Faculty.find(params[:id]) @students = @faculty.students end end * ``app/views/faculties/show.html.erb`` .. code-block:: erb

Faculties#show

<%= @faculty.name %>

<% @students.each do |student| %> <% end %>
<%= student.id %> <%= student.name %>
.. _ex16-answer: .. admonition:: 課題16 :class: exercise * ``app/controllers/course_controller.rb`` .. code-block:: ruby class CoursesController < ApplicationController def index @courses = Course.all end def show @course = Course.find(params[:id]) end end * ``app/views/courses/index.html.erb`` .. code-block:: erb

Courses#index

<% @courses.each do |course| %> <% end %>
<%= course.name %> <%= link_to '詳細', course_path(course) %>
* ``app/views/courses/show.html.erb`` .. code-block:: erb

Courses#show

科目名: <%= @course.name %>

単位数: <%= @course.credit %>

<% if @course.compulsory %> 必修科目 <% else %> 選択科目 <% end %>

<%= link_to 'Back', courses_path %> * ``config/routes.rb`` .. code-block:: ruby Rails.application.routes.draw do resources :courses, only: [ :index, :show ] resources :faculties, only: [ :show ] resources :students end .. _ex18-answer: .. admonition:: 課題18 :class: exercise .. code-block:: erb <%= form_with(model: student) do |form| %> <% if student.errors.any? %>

<%= pluralize(student.errors.count, "error") %> prohibited this student from being saved:

    <% student.errors.each do |error| %>
  • <%= error.full_message %>
  • <% end %>
<% end %>
<%= form.label :name, style: "display: block" %> <%= form.text_field :name %>
<%= form.label :faculty, style: "display: block" %> <%= form.collection_select :faculty_id, Faculty.all, :id, :name %>
<%= form.label :grade, style: "display: block" %> <% for i in 1..4 %> <%= form.radio_button :grade, i %> <%= form.label :grade, "#{i}年", value: i %> <% end %>
<%= form.submit %>
<% end %> .. comment