0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

# 【Ruby学習記録】Day 2:Rubyの基礎を幅広く学習

Posted at

【Ruby学習記録】Day 2:Rubyの基礎を幅広く学習

本日はRubyの文法について、基本的な概念から少し応用的な内容まで幅広く学びました。
以下に学んだことを、関連性がある順に整理してまとめておきます。


1. 配列と要素

fruits = ["apple", "banana", "orange"]
puts fruits[0]  # => apple
配列は複数のデータを一つにまとめて扱えるオブジェクトです

[]で囲んで定義しインデックス0から始まるで要素を取り出します

2. 配列演算子

a = [1, 2, 3]
b = [3, 4, 5]

puts a + b  # => [1, 2, 3, 3, 4, 5]
puts a - b  # => [1, 2]
puts a & b  # => [3]
puts a | b  # => [1, 2, 3, 4, 5]
+配列の結合

-差集合aにあってbにない要素

&積集合共通要素

|和集合重複を除いた全要素

3. ハッシュとシンボル

person = { name: "Taro", age: 25 }
puts person[:name]  # => Taro
ハッシュはキーと値のペアでデータを管理します

:name のようなキーはシンボルと呼ばれ軽量な文字列のようなものです

4. 比較演算子と論理演算子

x = 10
y = 5

puts x > y     # => true
puts x == y    # => false
puts x != y    # => true

puts x > 5 && y < 10  # => true
puts x < 5 || y < 10  # => true
比較演算子==, !=, >, <, >=, <=

論理演算子&&, ||, !

5. 条件分岐if

score = 80

if score >= 90
  puts "Excellent!"
elsif score >= 70
  puts "Good!"
else
  puts "Keep trying!"
end
条件によって処理を分けることができます

6. ループ処理
timesメソッド

3.times do |i|
  puts "Hello #{i}"
end
eachメソッド

["a", "b", "c"].each do |item|
  puts item
end
7. メソッド定義引数戻り値return

def greet(name)
  return "Hello, #{name}!"
end

puts greet("Taro")  # => Hello, Taro!
def でメソッドを定義します

return を使うことで戻り値を明示できます省略可能)。

8. スコープ変数の有効範囲

message = "Hello"

def say
  local_message = "Hi"
  puts local_message
end

say
# puts local_message  # エラー(スコープ外)
メソッドの中で定義した変数はその外では使えません

9. クラスとインスタンスなぜ必要?)

class Dog
end

dog1 = Dog.new
dog2 = Dog.new
クラスはオブジェクトの設計図インスタンスは実体

同じ性質を持つオブジェクトを複数扱う時に便利

10. 属性とインスタンス変数initializeメソッド

class Dog
  def initialize(name, age)
    @name = name
    @age = age
  end

  def info
    "#{@name} is #{@age} years old"
  end
end

dog = Dog.new("Pochi", 3)
puts dog.info
@がついた変数はインスタンス変数と呼ばれクラス内でオブジェクトごとに保持されます

initialize  new 実行時に呼ばれる特別なメソッド

11. クラスメソッドとインスタンスメソッドの違い

class Tool
  def self.class_method
    "これはクラスメソッド"
  end

  def instance_method
    "これはインスタンスメソッド"
  end
end

puts Tool.class_method
tool = Tool.new
puts tool.instance_method
self. をつけるとクラスメソッドそれ以外はインスタンスメソッド

12. ローカル変数とインスタンス変数の違い

def sample_method
  local_var = "ローカル変数"
  @instance_var = "インスタンス変数"
end
ローカル変数そのスコープ内でのみ有効

インスタンス変数オブジェクト内で共有される変数(@をつける

今日のまとめ
Rubyの基本的な文法を一通り学びました
特にオブジェクト指向の考え方クラスやインスタンスは少し難しかったですが
設計図と実体というイメージで少しずつ理解できてきた気がします
明日からはメソッドやクラスを組み合わせた実践的なコードにも挑戦していきます
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?