LoginSignup
1
1

More than 3 years have passed since last update.

Ruby入門メモ(プログラミング経験者用)2

Last updated at Posted at 2020-04-03

TIPS

定数

英大文字で定義する(慣習的に全部大文字)。

VERSION = 1.1

オブジェクトの型変換

to_i : 数値変換
to_f : 浮動小数点変換
to_s : 文字列変換

number = 100
f_number = number.to_i * 0.01
l_number = number.to_s + "円"
d_number = f_number.to_i

puts "#{number} #{f_number} #{l_number} #{d_number}"

[実行結果]

100 1.0 100円 1

書式付きの値埋め込み

%d 整数
%f 浮動小数
%s 文字列

puts "文字列と書式埋め込み" %[対応する値]
※埋め込む書式が複数なら配列で渡す。

diagram = "円"
radius = 1
ratio = 3.14

puts "半径%dcmの%sの直径は%.2fcmです" %[radius, diagram, 2 * ratio * radius]

[実行結果]

半径1cmの円の直径は6.28cmです

ハッシュ

C#でいう辞書、連想配列。
keyとそれに対応する値(value)をもつ。
型は数値でも文字列でも可能

presents = {"日本" => "お肉券" , "米国" => "お金", "英国" => "お金" }
puts presents["日本"]

awards = { 1 => "金" , 2 => "銀" , 3 => "銅" }
puts awards[1]

[実行結果]

お肉券
金

ハッシュのメソッド

size :サイズを返す
keys :キーを返す
values :値を返す

presents = {"日本" => "お肉券" , "米国" => "お金", "英国" => "お金" }

puts presents.size
puts "-----------------"
puts presents.keys
puts "-----------------"
puts presents.values
puts "-----------------"

[実行結果]

3
---------------------
日本
米国
英国
---------------------
お肉券
お金
お金
---------------------

Case

CやC#のswitch文に対応する。

case 変数
 when パターン1
    処理
 when パターン2
    処理
 end
input = gets.chomp

case input 
  when "red"
    puts "止まれ!"
  when "yellow"
    puts "警戒!"
#条件を複数扱いたいときはコンマで区切る
  when "blue","green"
    puts "進め"    
  end

[実行結果]

red
止まれ!

ループ

for文は入門メモ1参照

while

while 条件 do
  処理
end
input = gets.chomp.to_i
i = 0

while i < input do
  puts "あ"
  i += 1
end

[実行結果]

3
あ
あ
あ

途中でループ処理から抜けたいときは「break」
一回ループをスキップするときは「next」
条件文(if文)と共に扱うことが多い。

times

ループする回数が決まっているときに使う。

回数.times do |変数|
 処理
end
input = gets.chomp.to_i

input.times do |x|
  puts "あ"
end

[実行結果]

3
あ
あ
あ

参考文献

Progate https://prog-8.com/slides?lesson=72%2C75%2C78%2C81%2C85
ドットインストール https://dotinstall.com/lessons/basic_ruby_v3

1
1
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
1
1