Ruby 入門 -5ページ目

Ruby 入門

~ Ruby初心者による逆引き備忘録 ~

<< 目次

配列の先頭、または、最後に要素を追加する。

array1 = [ "a", "b", "c"]

p array1

array1.push("d")

p array1

array1 << "e"

p array1

array1.unshift("f")

p array1

実行結果

["a", "b", "c"]
["a", "b", "c", "d"]
["a", "b", "c", "d", "e"]
["f", "a", "b", "c", "d", "e"]


<< 目次
<< 目次

配列を定義する。

array1 = [ "a", "b", "c"]
array2 = [ 1, 2, 3]
array3 = [ "a", 1, "b", 2, "c", 3]

p array1
p array2
p array3

実行結果

["a", "b", "c"]
[1, 2, 3]
["a", 1, "b", 2, "c", 3]


<< 目次
<< 目次

while ~ end で書く。

i = 0
while i < 5
puts i
i += 1
end

実行結果

0
1
2
3
4


while といえば、break である。
意味がないけど強引に以下のように使ってみる。

i = 0
while i < 5
puts i
i += 1
if i == 2
break
end
end

実行結果

0
1


さらに、while による無限ループをつくってみた。
sleep 1 で 1秒の wait を行っている。

while true
puts "while test"
sleep 1
end

実行結果

while test
while test
while test
.
.
.


<< 目次
<< 目次

定番のif文。
"else if" の辺りが言語によって書き方が違ったりするのでよく間違えるので注意。
ruby では、 "elsif" となる。

a = 1
b = 2
if a == 2
puts "a = 2"
elsif b == 2
puts "b = 2"
else
puts "not much."
end

実行結果

b = 2


よく間違える判定条件 "=" が後ろに来ることを心がける。

a == b
a >= b
a <= b

">=" を "=>" とか書くと syntax error になる。

syntax error, unexpected '>'


<< 目次
<< 目次

一行コメントアウトは、他の言語でも使われております一般的な"#"を使います。
"#" 以降が無視されます。

複数行をコメントアウトする時は、
=begin ~ =end を使います。

puts "comment test start"
=begin
puts "この間は"
puts "何を書いても無視されます。"
=end
puts "comment test end"


実行結果

comment test start
comment test end


<< 目次
<< 目次

"+" でつなぐ。

str1 = "mo"
str2 = "ji"

moji = str1 + str2
p moji # => "moji"


"#{}" で埋め込む。

str1 = "mo"
str2 = "ji"

moji = "#{str1}#{str2}"
p moji # => "moji"


<< 目次
<< 目次

クラス変数を一覧表示する。

class Test

def initialize
@var1 = 1
@var2 = 2
@var3 = 3
end

end

test = Test.new
p test.instance_variables


実行結果

["@var1", "@var3", "@var2"]


<< 目次