LoginSignup
0
1

More than 5 years have passed since last update.

Ruby 学習 基本(文字列 変数 配列)

Last updated at Posted at 2019-02-21

はじめに

Rubyの学習を始めました。学んだことを忘れないように備忘録として残しています。

Ruby基本

 文字列

1 文字列は半角クォーテーションで囲む


     puts "Hello World"    # Hello World
     puts 'Hello World'    # Hello World

2 文字列と数値の違い

    puts 5 + 2   # 7
    puts '5 + 2' # '5 + 2'

3 文字列の連結


    puts 'I am' + 'Japanese.' # I am Japanese
    puts '2' + '5'            # 25
    puts 2 + 5                # 7

 変数

1 変数の定義
 変数名 = 値
2 文字列の入った変数の連結



   message = 'Hi!'
   name = 'Mark'
   puts message + name   # Hi!Mark

3 数値が入った変数


  num1 = 5
  puts num1 + 3     # 8
  num2 = 6
  puts num1 + num2  #11

4 変数名のルール
 ※英単語を用いる
 ※2語以上の場合はアンダーバー(_)で区切る
 ※数字開始はエラーになる 1Name...☓

5 変数更新


  num = 3
  puts num       # 3
  num = num + 5
  puts num       #8

*省略した書き方
x = x + 10  →  x += 10
x = x - 10  →  x -= 10
x = x * 10  →  x *= 10
x = x / 10  →  x /= 10
x = x % 10  →  x %= 10

6 変数を文字列に含める
 文字列の中で#{変数名}とすることで変数を代入している値に置き換えて、文字列に含めることができる。これを変数展開と呼ぶ。
注意点 ダブルクォーテーションを使った文字列の場合しか変数展開はされない。シングルクォーテーションの場合は変数展開が行われずにそのまま文字列と出力されてしまう。



  name = 'Ken'
  puts "Hello!#{name}!" # Hello!Ken!
  puts 'Hello!#{name}!' # Hello!#{name}!

 配列[インデックス]


colors = ["black","red","orange","white","yellow"]
 p colors[0] # black
 p colors[-1] # 末尾yellow [-2]とするとwhite
 p colors[0..2] # 0-2まで black red orange
 p colors[0...2] # 0-2の直前まで black red
 p colors[6] #nil
 p colors.push("gold") # goldが追加される
 p colors << "silver" # silverが追加される

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