【未経験プログラミング】Rubyのおさらい【20日目/21日目】
integrer = 1.to_s 文字列 "1"
strings = 1.to_i 数値 1
puts '#{1+1}' =#{1+1} Rubyの式として評価しない
puts "#{1+1}" =2 Rubyの式として評価
省略 %w(#{1+1}) =#{1+1}
%W(#{1+1}) =2
1と'1'は数値と文字列で別の解釈
irb p 1 p'1'
1.class integer
'1'.class String
pメソッド 主にテスト用途で使用。データの種類がわかりやすい。
putsメソッド 単に画面に表示して改行する用途で使用。
データの種類 integer(10),float(10.1),String('10'),Class(String),
True class/false class(true),hash(#),Array([]),nillclass(nil)
animals = ['dog', 'cat', 'mouse']
animals << 'cats'
p animals => ["dog", "cat", "mouse", "cats"]
animals = ['dog', 'cat', 'mouse']
p animals[2] => "mouse"
animals = ['dog', 'cat', 'mouse']
animals[2] = 'human'
p animals => ["dog", "cat", "human"]
animals = ['dog', 'cat', 'mouse']
animals.delete('cat')
p animals => ["dog", "mouse"]
animals = ['dog', 'cat', 'mouse']
animals.insert(2,'bird')
p animals => ["dog", "cat", "bird", "mouse"]
rubyの配列要素は[要素1,要素2,要素3]で表現します。
ハッシュ{} = 連想配列 {}=波括弧
child = {height: 150, weight:50}
child[:age] = 7 キーと値
p child
p child [:age]
=>
150
50
{:height=>150, :weight=>50, :age=>7}
7
child = {height: 150, weight:50, age:5 }
child.store(:age, 7)
p child => {:height=>150, :weight=>50, :age=>7}
%記法
%w(文字列式展開無) ,%i(シンボル式展開無),%W(文字列式展開有) ,%I(シンボル式展開有)
"dog" :dog
クォーテーション、カンマ、コロン、など省略できる。.
a = %W(#{1+1} #{1+2})
p a =>["2", "3"]
a = 0
if a == 1
p 'aに1が代入されていたら実行される。'
else
p 'aに1が代入されていなかったら実行される'
end => "aに1が代入されていなかったら実行され