layout: post title: “2018-01-19-study-ruby-note” date: 2018-01-19 15:34:28 +0000
すごく途中
メモ
- Ruby: オブジェクト指向のプログラミング言語
- ri: オブジェクトドキュメントのコマンド ex. ri Array
- irb -> p “text” -> => “text” -> exit // すぐに実行結果 exit は irb 終了## コメントを書く
# 一行コメント=begin
複数行コメント
複数行コメント
複数行コメント
=end
実行結果
(画面上には表示されない)
文字列の表示
次と繋がりながら文字列が表示される
print "Hello,World!!"
実行結果
Hello,World!!user:~/workspace $
```#### 改行されて文字列が表示される
puts “Hello,World!!”
#### 実行結果
Hello,World!!
user:~/workspace $
“`#### “”(クォーテーションマーク) もついて文字列が表示される(デバッグ用)
p "Hello,World!!"
実行結果
"Hello,World!!"
user:~/workspace $
```## 変数
#### Ruby の変数は英子文字 or _(アンダーバー) はじまりで書く
msg = “Hello,World!!”
puts msg
#### 実行結果
“Hello,World!!”
“`## 定数
Ruby の定数は全て英大文字で書く
VERSION = 1.5
puts VERSION
実行結果
1.5
```## Ruby の特徴
Ruby ではすべての値がオブジェクトになっている。
オブジェクトとは便利な命令をいろいろ持っているデータ型のこと。### String Class
#### .length は文字列の文字数を表すメソッド(JSに同じ)
msg = “Hello,World!!”.length
puts msg
#### 実行結果
13
“`#### .reverse はその名の通り逆順にして文字列を返すメソッド
msg = "Hello,World!!".reverse
puts msg
実行結果
!!dlroW,olleH
```### Float Class(フロートクラス) に属するメソッド
#### .round は小数点以下を四捨五入する
msg = 1.5.round
puts msg
#### 実行結果
2
“`#### .floor は小数点以下を切り捨てる
msg = 1.5.floor
puts msg
実行結果
1
```### ところで Class(クラス) と Instance(インスタンス) とは?
>生徒(インスタンス)は漏れなく学級(クラス)に属しています学級(クラス)には、学級ごとのルールがある
生徒(インスタンス)は、学級(クラス)のルールに従って行動(メソッド)を起こす
生徒(インスタンス)は、このルールによって、行動(メソッド)が限定される
つまり、インスタンスは、クラスによって使えるメソッドが違うということ

クラスとインスタンスのまとめ - mic_footprintsRubyをはじめたころの自分の記事が意外にも分かりやすかったので、改変して再掲載しますw クラスメソッドとインスタンスメソッド - mic_footprints ☆クラスメソッド クラスとは クラスとは、オブジェクトの種類を表したもの つま...## 数値
数値を扱う前にオブジェクトがどのクラスに属していて、どんなメソッドを持っているか調べるには以下を実行。
p 8.8.class
p 8.8.methods
#### 実行結果
Float
[:%, :*, :+, :-, :/, :<, :>, :-@, :**, :<=>, :<=, :>=, :==, :===, :eql?, :inspect, :to_int, :to_s, :to_i, :to_f, :hash, :coerce, :divmod, :fdiv, :modulo, :abs, :magnitude, :zero?, :floor, :ceil, :round, :truncate, :positive?, :negative?, :quo, :nan?, :infinite?, :finite?, :next_float, :prev_float, :to_r, :numerator, :denominator, :rationalize, :arg, :angle, :phase, :+@, :singleton_method_added, :div, :i, :remainder, :real?, :integer?, :nonzero?, :step, :rectangular, :rect, :polar, :real, :imaginary, :imag, :abs2, :conjugate, :conj, :to_c, :between?, :instance_of?, :public_send, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :private_methods, :kind_of?, :instance_variables, :tap, :method, :public_method, :singleton_method, :is_a?, :extend, :define_singleton_method, :to_enum, :enum_for, :=~, :!~, :respond_to?, :freeze, :display, :object_id, :send, :nil?, :class, :singleton_class, :clone, :dup, :itself, :taint, :tainted?, :untaint, :untrust, :trust, :untrusted?, :methods, :protected_methods, :frozen?, :public_methods, :singleton_methods, :!, :!=, :send, :equal?, :instance_eval, :instance_exec, :id]
…(';')…???### 足し算(+)
p 10 + 5
#### 実行結果
15
“`### 掛け算(*)
p 3.5 * 5
実行結果
17.5
```### 割り算(/)
p 10 / 5
#### 実行結果
2
“`### 余り(%)
p 10 % 5
実行結果
0
```### 分数
p Rational(2,5) # 5分の2のこと
p 2/5r # 上記と同じ意味の別表記
#### 実行結果
(2/5)
“`### 分数の計算
p Rational(2,5) + Rational(3,4)
p 2/5r + 3/4r # 上記と同じ意味の別表記
実行結果
(23/20)
```### 数値に .round メソッド
p 23.6.round
#### 実行結果
24
“`### 数値に .floor メソッド
p 23.6.floor
実行結果
23
```### 数値に .ceil メソッド
p 23.6.ceil
#### 実行結果
24
“`## 文字列オブジェクト
- “”(クォーテーション) で囲うと特殊文字や式展開が可能
- ”(シングルクォーテーション) ではできない### 特殊文字
puts "hellono worltd" puts 'hellono worltd'
実行結果
hello o worl d hellono worltd ```### 式展開
puts “price #{2000 5}”
puts ‘price #{2000 5}’#### 実行結果
price 10000
price #{2000 * 5}
“`### 変数展開name = "dareka" puts "hello #{name}"
実行結果
hello dareka ```### 文字列オブジェクトメソッド
puts “hello” + “world”
puts “hello” * 10#### 実行結果
helloworld
hellohellohellohellohellohellohellohellohellohello
“`## ! メソッドについて
そのもの破壊的メソッドとも呼ばれる - upcase – 文字列を大文字にして返す
- upcase! – 文字列を大文字にして返し、元の文字列も大文字にして返す
- downcase – 文字列を小文字にして返す
- reverse – 文字列を逆順にして返す
name = "namae" puts name.upcase puts name puts name.upcase! puts name
実行結果
NAMAE namae NAMAE NAMAE ```## ? メソッドについて true or false の真偽値を返すメソッド ### 文字列は空か調べる
name = “namae”
p name.empty?#### 実行結果
false
“`### 指定された文字が含まれているかname = "namae" p name.include?("n")
実行結果
true ```## 配列 複数のオブジェクトをまとめられる配列オブジェクト
colors = [“red”, “blue”, “yellow”, “green”]
p colors[0]
p colors[2]
p colors[-1]
p colors[0..2]
p colors[0…2]
p colors[5]“`実行結果
"red" # 0 番目 "yellow" # 2 番目 "green" # 0 から数えて -1 番目なので "green" ["red", "blue", "yellow"] # 0-2 番目までを表示 ["red", "blue"] # 2 番目の直前 nil # 5 番目は無いよ
※ちなみに [0] の部分は”添え字”という### 書き換え
colors = ["red", "blue", "yellow", "green"] colors[0] = "purple" colors[1..2] = ["white", "black"] p colors
実行結果
["purple", "white", "black", "green"] # 0 番目 と 1-2 番目が書き換わっている### push で末尾に文字列を追加
colors = [“red”, “blue”, “yellow”, “green”]
colors[0] = “purple”
colors[1..2] = [“white”, “black”]colors.push(“gold”) # 要素の末尾に文字列を追加する
colors << “silver” # 上記に同じp colors#### 実行結果
[“purple”, “white”, “black”, “green”, “gold”, “silver”] # 末尾に色が増えている
“`### 文字列の個数colors = ["red", "blue", "yellow", "green"] p colors.size
実行結果
4 ```### ソート(アルファベット順などに並び替え)
colors = [“red”, “blue”, “yellow”, “green”]
p colors.sort#### 実行結果
[“blue”, “green”, “red”, “yellow”]
“`## ハッシュオブジェクト値をまとめられるオブジェクト。例えば okojon 100 点、 mimi 400 点とスコアを表す際、以下の表記どれでも同じ意味で値をまとめておける。※下に行くほど省略形scores = {“okojon” => 100, “mimi” => 400}
scores = {:okojon => 100, :mimi => 400}
scores = {okojon: 100, mimi: 400}ex.
p scores[:okojon]
scores[:mimi] = 800 // 試しに書き換えてみる
p scoresex.
p scores.size // 要素の数(実行結果: 2)
p scores.keys // キーの一覧(実行結果: [:okojon, :mimi])
p scores.values // 値の一覧(実行結果: [100, 400])
p scores.has_key?(:okojon) // 指定したキーがあるかどうか(実行結果: true)おまけ
- to_s テキストとして値を利用する
- to_i 整数として値を利用する