「よくわかるRuby on Rails入門」サポートサイト

このページは、世界最大級のオンライン学習プラットフォームUdemy(ユーデミー)「よくわかるRuby on Rails入門-RubyとRailsを基礎から学びWebアプリケーションをネットに公開しよう」と、Proglus(プログラス)受講生の方向けサポートサイトです。

コースの学習で使用したサンプルコードを掲載しています(一部除く)。
エラーが発生した時に見比べたり、動作するコードをコピー&ペースとして実行したいときなど、個人の学習用にご利用ください。

Ruby 2.5.1, Ruby on Rails 5.2.1にて動作確認をしております。その他の環境では動作が異なる場合があります。

ご意見、ご質問はUdemy、ProglusのQ&Aコーナーをご利用ください。

目次

よくあるご質問

Q. 開発環境に、AWS Cloud9を使わなくても良いですか?
A. はいOKです。ただし、macOSとWindws7,8,10で発生する手順が異なってくるため、よくわからない方は、ひとまずCloud9(1年無料枠)をご利用いただくことをおすすめしています。個別の環境に依存する内容のサポートはできない場合があります。

Q. Windows環境でRuby installerを使用して環境構築をしたのですが、サンプルコードが動作しません。
A. Ruby installerは何かとトラブルが多いようです。このコースでは、Ruby installerはサポートしていません。

はじめてのRuby入門

はじめてのRubyプログラム①

$ irb
2.5.1 :001 > 'Hello, World!'
 => "Hello, World!" 
2.5.1 :002 > puts 'Hello, World!'
Hello, World!
 => nil 
2.5.1 :003 > 1 + 1
 => 2 
2.5.1 :004 > 10 - 1
 => 9 
2.5.1 :005 > 
2.5.1 :005 > exit

はじめてのRubyプログラム②

puts 'Hello, World!'
puts 10 + 3

演習 : Hello, Ruby!①

$ irb
2.5.1 :001 > 'Hello, World!'
 => "Hello, World!" 
2.5.1 :002 > puts 'Hello, World!'
Hello, World!
 => nil 
2.5.1 :003 > 1 + 1
 => 2 
2.5.1 :004 > 10 - 1
 => 9 
2.5.1 :005 > 
2.5.1 :005 > exit

演習 : Hello, Ruby!②

hello_ruby.rb

puts 'Hello, Ruby!'

コメント

comment.rb

# puts 'Hello, World!'

=begin
puts 'Hello, World!'
puts 'Hello, World!'
puts 'Hello, World!'
=end

# puts 'Hello, World!'
# puts 'Hello, World!'
# puts 'Hello, World!'

# This is a comment.

変数(ローカル変数)

$ irb
2.5.1 :001 > s = 'Hello!'                                                 
 => "Hello!" 
2.5.1 :002 > puts s
Hello!
 => nil 
2.5.1 :003 > n = 10 * 2
 => 20 
2.5.1 :004 > puts n
20
 => nil 
2.5.1 :005 > i
Traceback (most recent call last):
        2: from /usr/local/rvm/rubies/ruby-2.5.1/bin/irb:11:in `
' 1: from (irb):5 NameError (undefined local variable or method `i' for main:Object) 2.5.1 :006 > i = nil => nil 2.5.1 :007 > exit

変数の命名規則

$ irb
2.5.1 :001 > price = 100
 => 100 
2.5.1 :002 > price1 = 100
 => 100 
2.5.1 :003 > _price = 100
 => 100 
2.5.1 :004 > 1price = 100
Traceback (most recent call last):
        1: from /usr/local/rvm/rubies/ruby-2.5.1/bin/irb:11:in `
' SyntaxError ((irb):4: syntax error, unexpected tIDENTIFIER, expecting end-of-input) 1price = 100 ^~~~~ 2.5.1 :005 > price_cost = 100 => 100 2.5.1 :006 > priceCost = 100 => 100 2.5.1 :007 > exit

定数

準備中

数値(Numeric)

$ irb
2.5.1 :001 > 100
 => 100 
2.5.1 :002 > -50
 => -50 
2.5.1 :003 > 2.5
 => 2.5 
2.5.1 :004 > -5.25
 => -5.25 
2.5.1 :005 > 1 + 1
 => 2 
2.5.1 :006 > 10 - 1
 => 9 
2.5.1 :007 > 13 * 2
 => 26 
2.5.1 :008 > 100 / 5
 => 20 
2.5.1 :009 > x = 1
 => 1 
2.5.1 :010 > -x
 => -1 
2.5.1 :011 > 
2.5.1 :011 > 3 / 2
 => 1 
2.5.1 :012 > 3.0 / 2
 => 1.5 
2.5.1 :013 > 3 / 2.0
 => 1.5 
2.5.1 :014 > 3.0 / 2.0
 => 1.5 
2.5.1 :015 > 10 % 3
 => 1 
2.5.1 :016 > 10 ** 3
 => 1000 
2.5.1 :017 > x = 3
 => 3 
2.5.1 :018 > x.to_f
 => 3.0 
2.5.1 :019 > x.to_f / 2
 => 1.5 
2.5.1 :020 > x / 2
 => 1 
2.5.1 :021 > y = 2
 => 2 
2.5.1 :022 > x / y.to_f
 => 1.5 
2.5.1 :023 > x.to_f / y
 => 1.5 
2.5.1 :024 > x.to_f / y.to_f
 => 1.5 
2.5.1 :025 > 1.class
 => Integer 
2.5.1 :026 > 1.1.class
 => Float 
2.5.1 :027 > 1.methods
 => [:-@, :**, :<=>, :upto, :<<, :<=, :>=, :==, :chr, :===, :>>, :[], :%, :&, :inspect, :+, :ord, :-, :/, :*, :size, :succ, :<, :>, :to_int, :coerce, :divmod, :to_s, :to_i, :fdiv, :modulo, :remainder, :abs, :magnitude, :integer?, :numerator, :denominator, :rationalize, :to_r, :floor, :ceil, :round, :truncate, :lcm, :to_f, :^, :odd?, :even?, :allbits?, :anybits?, :nobits?, :downto, :times, :pred, :pow, :bit_length, :digits, :gcd, :gcdlcm, :next, :div, :|, :~, :+@, :eql?, :singleton_method_added, :i, :real?, :zero?, :nonzero?, :finite?, :infinite?, :step, :positive?, :negative?, :rectangular, :rect, :arg, :real, :imag, :imaginary, :angle, :abs2, :conjugate, :to_c, :polar, :conj, :phase, :clone, :dup, :quo, :between?, :clamp, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :instance_of?, :kind_of?, :is_a?, :tap, :instance_variable_get, :public_methods, :instance_variables, :public_method, :singleton_method, :method, :define_singleton_method, :public_send, :extend, :to_enum, :enum_for, :pp, :=~, :!~, :respond_to?, :freeze, :object_id, :send, :display, :nil?, :hash, :class, :singleton_class, :itself, :yield_self, :tainted?, :taint, :untrust, :untaint, :trust, :untrusted?, :methods, :frozen?, :protected_methods, :singleton_methods, :private_methods, :!, :equal?, :instance_eval, :instance_exec, :!=, :__id__, :__send__] 
2.5.1 :028 > exit

文字列(String) ①

$ irb
2.5.1 :001 > 'abcdef'
 => "abcdef" 
2.5.1 :002 > "abcdef"
 => "abcdef" 
2.5.1 :003 > puts "Ruby\nProgramming"
Ruby
Programming
 => nil 
2.5.1 :004 > puts 'Ruby\nProgramming'
Ruby\nProgramming
 => nil 
2.5.1 :005 > first_name = 'Yuta'
 => "Yuta" 
2.5.1 :006 > last_name = 'Nakamura'
 => "Nakamura" 
2.5.1 :007 > puts "My name is #{first_name} #{last_name}."
My name is Yuta Nakamura.
 => nil 
2.5.1 :008 > puts 'My name is #{first_name} #{last_name}.'                    
My name is #{first_name} #{last_name}.
 => nil 

文字列②

2.5.1 :009 > puts 'Yuta' + 'Nakamura'
YutaNakamura
 => nil 
2.5.1 :010 > puts 'Yuta' + ' ' + 'Nakamura'                                   
Yuta Nakamura
 => nil 
2.5.1 :011 > s = 'Hello, World!'
 => "Hello, World!" 
2.5.1 :012 > puts s.upcase
HELLO, WORLD!
 => nil 
2.5.1 :013 > puts s
Hello, World!
 => nil 
2.5.1 :014 > s.upcase!
 => "HELLO, WORLD!" 
2.5.1 :015 > puts s
HELLO, WORLD!
 => nil 
2.5.1 :016 > 'abc'.class
 => String 
2.5.1 :017 > 'abc'.method
Traceback (most recent call last):
        3: from /usr/local/rvm/rubies/ruby-2.5.1/bin/irb:11:in `
' 2: from (irb):17 1: from (irb):17:in `method' ArgumentError (wrong number of arguments (given 0, expected 1)) 2.5.1 :018 > 'abc'.methods => [:encode!, :include?, :%, :*, :+, :count, :partition, :to_c, :sum, :next, :casecmp, :casecmp?, :insert, :bytesize, :match, :match?, :succ!, :<=>, :next!, :index, :rindex, :upto, :==, :===, :chr, :=~, :byteslice, :[], :[]=, :scrub!, :getbyte, :replace, :clear, :scrub, :empty?, :eql?, :-@, :downcase, :upcase, :dump, :setbyte, :swapcase, :+@, :capitalize, :capitalize!, :undump, :downcase!, :oct, :swapcase!, :lines, :bytes, :split, :codepoints, :freeze, :inspect, :reverse!, :grapheme_clusters, :reverse, :hex, :scan, :upcase!, :crypt, :ord, :chars, :prepend, :length, :size, :start_with?, :succ, :sub, :intern, :chop, :center, :<<, :concat, :strip, :lstrip, :end_with?, :delete_prefix, :to_str, :to_sym, :gsub!, :rstrip, :gsub, :delete_suffix, :to_s, :to_i, :rjust, :chomp!, :strip!, :lstrip!, :sub!, :chomp, :chop!, :ljust, :tr_s, :delete, :rstrip!, :delete_prefix!, :delete_suffix!, :tr, :squeeze!, :each_line, :to_f, :tr!, :tr_s!, :delete!, :slice, :slice!, :each_byte, :squeeze, :each_codepoint, :each_grapheme_cluster, :valid_encoding?, :ascii_only?, :rpartition, :encoding, :hash, :b, :unicode_normalize!, :unicode_normalized?, :to_r, :force_encoding, :each_char, :encode, :unicode_normalize, :unpack, :unpack1, :<=, :>=, :between?, :<, :>, :clamp, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :instance_of?, :kind_of?, :is_a?, :tap, :instance_variable_get, :public_methods, :instance_variables, :public_method, :singleton_method, :method, :define_singleton_method, :public_send, :extend, :to_enum, :enum_for, :pp, :!~, :respond_to?, :object_id, :send, :display, :nil?, :class, :singleton_class, :clone, :dup, :itself, :yield_self, :tainted?, :taint, :untrust, :untaint, :trust, :untrusted?, :methods, :frozen?, :protected_methods, :singleton_methods, :private_methods, :!, :equal?, :instance_eval, :instance_exec, :!=, :__id__, :__send__] 2.5.1 :019 > exit

空白文字

$ irb
2.5.1 :001 > 10 + 2 - 1
 => 11 
2.5.1 :002 > 10+2-1
 => 11 
2.5.1 :003 > 10                 +                2       -        1
 => 11 
2.5.1 :004 > exit

比較演算子による値の比較

$ irb
2.5.1 :001 > 1 < 2
 => true 
2.5.1 :002 > 1 <= 2
 => true 
2.5.1 :003 > 1 > 2
 => false 
2.5.1 :004 > 1 == 1
 => true 
2.5.1 :005 > 1 != 2
 => true 
2.5.1 :006 > exit

数値と文字列は暗黙的に変換されない

 $ irb
2.5.1 :001 > 1.0 + 2.0 * 3.0 / 4.0
 => 2.5
2.5.1 :002 > (1.0 + 2.0) * 3.0 / 4.0
 => 2.25
2.5.1 :018 > exit

数値と文字列は暗黙的に変換されない

$ irb
2.5.1 :001 > 1 + '1'
Traceback (most recent call last):
        3: from /usr/local/rvm/rubies/ruby-2.5.1/bin/irb:11:in `
' 2: from (irb):1 1: from (irb):1:in `+' TypeError (String can't be coerced into Integer) 2.5.1 :002 > 1 + '1'.to_i => 2 2.5.1 :003 > 1 + '1.1'.to_f => 2.1 2.5.1 :004 > number = 1 => 1 2.5.1 :005 > 'Number is' + number Traceback (most recent call last): 3: from /usr/local/rvm/rubies/ruby-2.5.1/bin/irb:11:in `
' 2: from (irb):5 1: from (irb):5:in `+' TypeError (no implicit conversion of Integer into String) 2.5.1 :006 > 'Number is ' + number.to_s => "Number is 1" 2.5.1 :007 > exit

インクリメントとデクリメント

$ irb
2.5.1 :001 > n = 1
 => 1 
2.5.1 :002 > n = n + 1
 => 2 
2.5.1 :003 > n += 1
 => 3 
2.5.1 :004 > n = n - 1
 => 2 
2.5.1 :005 > n -= 1
 => 1 
2.5.1 :006 > exit

真偽値と論理演算子 ②

 $ irb
2.5.1 :001 > t1 = true
 => true 
2.5.1 :002 > t2 = true
 => true 
2.5.1 :003 > f1 = false
 => false 
2.5.1 :004 > f2 = false
 => false 
2.5.1 :005 > t1 && t2
 => true 
2.5.1 :006 > t1 && f1
 => false 
2.5.1 :007 > t1 || f1
 => true 
2.5.1 :008 > f1 || f2
 => false 
2.5.1 :009 > !t1
 => false 
2.5.1 :010 > !f1
 => true 
2.5.1 :011 > exit

and, or, not

$ irb
2.5.1 :001 > t1 = true
 => true 
2.5.1 :002 > t2 = true
 => true 
2.5.1 :003 > f1 = false
 => false 
2.5.1 :004 > f2 = false
 => false 
2.5.1 :005 > t1 && t2
 => true 
2.5.1 :006 > t1 and t2
 => true 
2.5.1 :007 > t1 && f1
 => false 
2.5.1 :008 > t1 and f2
 => false 
2.5.1 :009 > t1 || t2
 => true 
2.5.1 :010 > t1 or t2
 => true 
2.5.1 :011 > t1 || f2
 => true 
2.5.1 :012 > t1 or f2
 => true 
2.5.1 :013 > f1 || f2
 => false 
2.5.1 :014 > f1 or f2
 => false 
2.5.1 :015 > !t1
 => false 
2.5.1 :016 > not(t1)
 => false 
2.5.1 :017 > !f1
 => true 
2.5.1 :018 > not(f1)
 => true 
2.5.1 :019 > 
2.5.1 :019 > !t1 || t1
 => true 
2.5.1 :020 > not t1 || t1
 => false 
2.5.1 :021 > t1 || t2 && f1
 => true 
2.5.1 :022 > t1 or t2 and f1
 => false 
2.5.1 :023 > (t1 || t2) && f1
 => false 
2.5.1 :024 > exit

条件分岐 if 例題①

if.rb

score = 59
if score >= 90
  puts 'A'
elsif score >= 80
  puts 'B'
elsif score >= 60
  puts 'C'
else
  puts 'D'
end

条件分岐 if 例題②

if_animal.rb

animal = 'horse'
if animal == 'cat'
  puts 'meow'
elsif animal == 'dog'
  puts 'bowwow'
elsif animal == 'cow'
  puts 'moomoo'
else
  puts 'Not fount.'
end

演習回答:テーマパークの入場料計算

exercise_branch.rb

age = 5
if age >= 12
  puts '5,000'
elsif age >= 6
  puts '2,500'
else
  puts '1,000'
end

条件分岐 unless

unless.rb

# 例題①
# n = 1
# if !n.zero?
#   puts 'Not zero.'
# end

## 例題②, ③
n = 1
unless n.zero?
  puts 'Not zero.'
else
  puts 'This is zero.'
end

条件分岐 case

case.rb

# if
# stone = 'opal'
# if stone == 'ruby'
#   puts 'July'
# elsif stone == 'peridot'
#   puts 'August'
# elsif stone == 'sapphire'
#   puts 'September'
# else
#   puts 'Not Found'
# end

# case
stone = 'opal'
case stone
when 'ruby'
  puts 'July'
when 'peridot'
  puts 'August'
when 'sapphire'
  puts 'September'
else
  puts 'Not Found.'
end

メソッド

mehod_hello.rb

def hello_world
  puts 'Hello, World!'
end

hello_world

method_add.rb
def add(x, y)
  x + y
end

puts add(10, 1)

メソッドの命名規則

method_name.rb

# def hello
# def hello_world
# def hello_world1
# def 1hello_world
def _hello_world
  puts 'Hello'
end

_hello_world

演習回答:動物の鳴き声を出し分けるメソッド

exercise_method_animal.rb

def cry(animal)
  if animal == 'cat'
    'meow'
  elsif animal == 'dog'
    'bowwow'
  else 
    '???'
  end
end

puts cry('horse')

演習回答:FizzBuzzのメソッド

fizz_buzz.rb

def fizz_buzz(n)
  if n % 15 == 0
    'FizzBuzz'
  elsif n % 3 == 0
    'Fizz'
  elsif n % 5 == 0
    'Buzz'
  else 
    n.to_s
  end
  
end

puts fizz_buzz(1)
puts fizz_buzz(2)
puts fizz_buzz(3)
puts fizz_buzz(4)
puts fizz_buzz(5)
puts fizz_buzz(6)
puts fizz_buzz(7)
puts fizz_buzz(8)
puts fizz_buzz(9)
puts fizz_buzz(10)
puts fizz_buzz(11)
puts fizz_buzz(12)
puts fizz_buzz(13)
puts fizz_buzz(14)
puts fizz_buzz(15)

出力 puts, print , p, pp

$ irb
2.5.1 :001 > puts 'Nakamura'
Nakamura
 => nil 
2.5.1 :002 > print 'Nakamura'
Nakamura => nil 
2.5.1 :003 > p 'Nakamura'
"Nakamura"
 => "Nakamura" 
2.5.1 :004 > pp 'Nakamura'
"Nakamura"
 => "Nakamura" 
2.5.1 :005 > exit

配列

$ irb
2.5.1 :001 > a = [1, 2, 3, 'aa', [1, 2, 3]]
 => [1, 2, 3, "aa", [1, 2, 3]] 
2.5.1 :002 > a[0]
 => 1 
2.5.1 :003 > a[1]
 => 2 
2.5.1 :004 > puts a
1
2
3
aa
1
2
3
 => nil 
2.5.1 :005 > p a
[1, 2, 3, "aa", [1, 2, 3]]
 => [1, 2, 3, "aa", [1, 2, 3]] 
2.5.1 :006 > pp a
[1, 2, 3, "aa", [1, 2, 3]]
 => [1, 2, 3, "aa", [1, 2, 3]] 
2.5.1 :007 > a.empty?
 => false 
2.5.1 :008 > b = []
 => [] 
2.5.1 :009 > b.empty?
 => true 
2.5.1 :010 > a.include?('aa')
 => true 
2.5.1 :011 > a.include?('b')
 => false 
2.5.1 :012 > a.reverse
 => [[1, 2, 3], "aa", 3, 2, 1] 
2.5.1 :013 > a
 => [1, 2, 3, "aa", [1, 2, 3]] 
2.5.1 :014 > a.reverse!
 => [[1, 2, 3], "aa", 3, 2, 1] 
2.5.1 :015 > a
 => [[1, 2, 3], "aa", 3, 2, 1] 
2.5.1 :017 > a.shuffle
 => [3, 1, "aa", [1, 2, 3], 2] 
2.5.1 :018 > 
2.5.1 :018 > (0..25).to_a
 => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25] 
2.5.1 :019 > aa = (0..99).to_a.shuffle!
 => [67, 13, 56, 17, 34, 7, 97, 32, 25, 38, 11, 99, 33, 53, 82, 76, 92, 75, 70, 21, 9, 31, 36, 65, 88, 95, 23, 42, 61, 16, 1, 29, 90, 64, 4, 79, 59, 19, 60, 81, 78, 68, 37, 66, 0, 5, 77, 55, 46, 10, 72, 49, 83, 18, 80, 24, 94, 69, 73, 22, 58, 96, 91, 62, 8, 52, 47, 93, 35, 3, 51, 43, 28, 40, 41, 50, 48, 87, 98, 26, 27, 86, 6, 12, 84, 63, 39, 30, 14, 15, 20, 45, 89, 85, 2, 57, 44, 74, 71, 54] 
2.5.1 :020 > aa
 => [67, 13, 56, 17, 34, 7, 97, 32, 25, 38, 11, 99, 33, 53, 82, 76, 92, 75, 70, 21, 9, 31, 36, 65, 88, 95, 23, 42, 61, 16, 1, 29, 90, 64, 4, 79, 59, 19, 60, 81, 78, 68, 37, 66, 0, 5, 77, 55, 46, 10, 72, 49, 83, 18, 80, 24, 94, 69, 73, 22, 58, 96, 91, 62, 8, 52, 47, 93, 35, 3, 51, 43, 28, 40, 41, 50, 48, 87, 98, 26, 27, 86, 6, 12, 84, 63, 39, 30, 14, 15, 20, 45, 89, 85, 2, 57, 44, 74, 71, 54] 
2.5.1 :021 > 
2.5.1 :021 > z = (0..10).to_a
 => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
2.5.1 :022 > z << 20
 => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20] 
2.5.1 :023 > z
 => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20] 
2.5.1 :024 > z.push(30)
 => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30] 
2.5.1 :025 > z
 => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30] 
2.5.1 :026 > z.pop
 => 30 
2.5.1 :027 > z
 => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20] 
2.5.1 :028 > z.shift
 => 0 
2.5.1 :029 > z
 => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20] 
2.5.1 :030 > z << 3
 => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 3] 
2.5.1 :031 > z << 6
 => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 3, 6] 
2.5.1 :032 > z.uniq
 => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20] 
2.5.1 :033 > z
 => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 3, 6] 
2.5.1 :034 > z.uniq!
 => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20] 
2.5.1 :035 > z
 => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20] 
2.5.1 :036 > 
2.5.1 :036 > s = ['my', 'name', 'is', 'nakamura']
 => ["my", "name", "is", "nakamura"] 
2.5.1 :037 > s.join
 => "mynameisnakamura" 
2.5.1 :038 > s.join(' ')
 => "my name is nakamura" 
2.5.1 :039 > s.join('_')
 => "my_name_is_nakamura" 
2.5.1 :040 > s.sort
 => ["is", "my", "nakamura", "name"] 
2.5.1 :041 > s.sort.reverse
 => ["name", "nakamura", "my", "is"] 
2.5.1 :043 > s.sort!.reverse!
 => ["name", "nakamura", "my", "is"] 
2.5.1 :044 > s
 => ["name", "nakamura", "my", "is"] 
2.5.1 :045 > s.size
 => 4 
2.5.1 :046 > exit

ハッシュ

$ irb
2.5.1 :001 > {}
 => {} 
2.5.1 :002 > nakamura = {'name' => 'Nakamura', 'birthplace' => 'Nagano'}
 => {"name"=>"Nakamura", "birthplace"=>"Nagano"} 
2.5.1 :003 > puts nakamura['name']
Nakamura
 => nil 
2.5.1 :004 > puts nakamura['birthplace']
Nagano
 => nil 
2.5.1 :005 > nakamura['age'] = 20
 => 20 
2.5.1 :006 > puts nakamura
{"name"=>"Nakamura", "birthplace"=>"Nagano", "age"=>20}
 => nil 
2.5.1 :007 > nakamura['age'] = 21                                           
 => 21 
2.5.1 :008 > puts nakamura
{"name"=>"Nakamura", "birthplace"=>"Nagano", "age"=>21}
 => nil 
2.5.1 :009 > nakamura.delete('age')
 => 21 
2.5.1 :010 > puts nakamura
{"name"=>"Nakamura", "birthplace"=>"Nagano"}
 => nil 
2.5.1 :011 > 
2.5.1 :011 > sato = {name: 'Sato', birthplace: 'Tokyo'}
 => {:name=>"Sato", :birthplace=>"Tokyo"} 
2.5.1 :012 > puts sato[:name]
Sato
 => nil 
2.5.1 :013 > puts sato[:birthplace]
Tokyo
 => nil 
2.5.1 :014 > sato[:age] = 20
 => 20 
2.5.1 :015 > puts sato
{:name=>"Sato", :birthplace=>"Tokyo", :age=>20}
 => nil 
2.5.1 :016 > sato[:age] = 21
 => 21 
2.5.1 :017 > puts sato
{:name=>"Sato", :birthplace=>"Tokyo", :age=>21}
 => nil 
2.5.1 :019 > sato.delete(:age)
 => 21 
2.5.1 :020 > puts sato
{:name=>"Sato", :birthplace=>"Tokyo"}
 => nil 
2.5.1 :021 > 
2.5.1 :021 > sato.keys
 => [:name, :birthplace] 
2.5.1 :022 > sato.values
 => ["Sato", "Tokyo"] 
2.5.1 :023 > sato.has_key?(:name)
 => true 
2.5.1 :024 > sato.has_key?(:address)
 => false 
2.5.1 :025 > sato.size
 => 2 
2.5.1 :026 > exit

繰り返し処理 each, for

each.rb

# each
numbers = [1,2,3,4,5]
# numbers.each do |number|
#   puts number
# end

# numbers.each { |number|
#  puts number
# }

# numbers.each { |number| puts number }

# colors = ['red', 'green', 'blue']
# colors.each do |color|
#   puts color
# end

for number in numbers do 
  puts number
end

繰り返し処理 each ハッシュの場合

each_hash.rb

scores = { luke: 100, jack: 90, robert: 70 }

# scores.each do |k, v|
#   puts v
# end

# scores.each do |k, v|
#   puts "#{k}, #{v}"
# end

scores.each do |k, v|
  if v >= 80
    puts "#{k}, #{v}"
  end
end

繰り返し処理 loop

loop.rb

# ①loopメソッドを使って、 変数の値を0から1ずつ増やしながら出力。

# i = 0
# loop do
#   puts i
#   i += 1
# end

# ②whileで書き換える
# i = 0
# while true
#   puts i
#   i += 1
# end

# ③0から9まで出力するプログラムをloopを使って、書く。
# i = 0
# loop do
#   puts i
#   i += 1
#   break if i == 10
# end

# ④配列[1,2,3,4,5] の値が、奇数の場合のみ、画面に出力する処理。
# eachとnextを利用

numbers = [1, 2, 3, 4, 5]
numbers.each do |n|
  # next if n % 2 == 0
  # next if n.even?
  next if n.odd?
  puts n
end

繰り返し処理 while

while.rb

# 数字を0から9まで、10個出力するプログラム
# をwhileを使って書いてみましょう。
i = 0
while i < 10 do
  puts i
  i += 1
end

繰り返し処理 upto, downto

upto.rb

# 数値を10から14まで1づつ増やしながら、値を出力
# uptoを使用する

# 10.upto(14) { |n| puts n }

# 数値を14から10まで1づつ減らしながら、値を出力
# downtoを使用する
14.downto(10) { |n| puts n }

繰り返し処理 step

# ①数値を1から10まで2ずつ増やしながら出力する

# 1.step(10, 2) { |n| puts n }

# ②数値を10から1まで2ずつ減らしながら出力する

10.step(1, -2) { |n| puts n}

オリジナルのクラスを作成する

# Carクラスの作成
# メソッド  hello ・・・ helloと出力する機能

class Car
  def initialize(name)
    puts 'initialize'
    @name = name
  end
  
  def hello
    puts "Hello! I am #{@name}."
  end
end

car = Car.new('Kitt')
car.hello

karr = Car.new('Karr')
karr.hello

アクセサメソッド①、②

accessor.rb

# Carクラスの作成
# メソッド  hello ・・・ helloと出力する機能

class Car
  
  # attr_accessor :name
  # attr_reader :name
  attr_writer :name
  
  def initialize(name)
    # puts 'initialize'
    @name = name
  end
  
  def hello
    puts "Hello! I am #{@name}."
  end
  
  # def name
  #   @name
  # end
  
  # def name=(value)
  #   @name = value
  # end
  
end

car = Car.new('Kitt')
# car.hello
# car.@name NG
# puts car.name
# car.@name = 'Nakamura' NG
car.name = 'Nakamura'
# puts car.name

クラス変数, クラスメソッド

class_var.rb

class Car
  @@count = 0
  def initialize(name)
    @name = name
    @@count += 1
  end
  
  def hello
    puts "Hello! I am #{@name}. #{@@count} instance(s)."
  end
  
  def self.info
    puts "#{@@count} instance(s)."
  end
  
end

kitt = Car.new('Kitt')
# kitt.hello
Car.info

karr = Car.new('Karr')
# karr.hello
Car.info

nakamura = Car.new('Nakamura')
# nakamura.hello
Car.info

クラスと定数

class Car
  REGION = 'USA'
  @@count = 0
  def initialize(name)
    @name = name
    @@count += 1
  end
  
  def hello
    puts "Hello! I am #{@name}. #{@@count} instance(s)."
  end
  
  def self.info
    puts "#{@@count} instance(s). Region: #{REGION}"
  end
  
end

kitt = Car.new('Kitt')
# kitt.hello
Car.info

karr = Car.new('Karr')
# karr.hello
Car.info

nakamura = Car.new('Nakamura')
# nakamura.hello
Car.info

puts Car::REGION

クラスの継承

sub_class.rb

# 1. Userクラスを作成 。
# 2. 自己紹介するメソッド hello を追加
# 3. Userクラスを継承した、AdminUserクラスを作成
# 4. 管理者として自己紹介するメソッド admin_helloを追加

class User
  def initialize(name)
    @name = name
  end
  
  def hello
    puts "Hello! I am #{@name}."
  end
end

class AdminUser < User
  def admin_hello
    puts "Hello! I am #{@name} from AdminUser."
  end
  
  # def hello
  #   puts 'Admin!'
  # end
end

# nakamura = User.new('Nakamura')
# nakamura.hello
# nakamura.admin_hello

sato = AdminUser.new('Sato')
sato.hello
sato.admin_hello

メソッドの公開範囲

access.rb

class User
  def initialize(name)
    @name = name
  end
  
  def say
    hello
  end
  
  private
    def hello
      puts "Hello! I am #{@name}."
    end
    
    def hello2
    end
end

nakamura = User.new('Nakamura')
# nakamura.hello
nakamura.say

モジュール

module.rb

# 自動車の運転者に関するモジュールの作成
# Runと出力するメソッド
# Stopと出力するメソッド

module Driver
  def self.run
    puts 'Run'
  end
  
  def self.stop
    puts 'Stop'
  end
end

Driver.run
Driver.stop

# driver = Driver.new

# module TaxiDriver < Driver
# end

例外と例外処理

exception.rb

puts '--- Please enter an integer. ---'
i = gets.to_i

begin
  puts 10 / i
  puts "begin's end"
rescue => ex
  puts 'Error!'
  puts ex.message
  puts ex.class
ensure
  puts 'end'

end

【旧版:Rails5】はじめてのRuby on Rails入門

GitHubを参照してください:
>>こちらから

【旧版:Rails5】版ミニQ&Aアプリ

GitHubを参照してください:

>>こちらから

注意事項

受講生の皆さんの個人的な学習にのみご利用いただけます。
営利・非営利問わず二次利用する行為を禁止します。