0
0

Ruby基礎①

Posted at

久しぶりに勉強してみる

昔スクールで勉強したことあるが使う機会がなかったので全然使っていなかった。しかし意味働いているベンダーはRubyを使っているみたいだ。

親会社もグループ会社もRuby、最近だとサーバレスなフレームワークを使うみたいだが。TypeScriptをやった方がいいと言いつつRuby on Railsの需要もまだある。

公式は日本語もあるので学習しやすいだろう。
official

# 数値の123、文字列などをリテラルという。
# Rubyで使える例

# 数字
puts 123

# 文字列
puts "Hi"

# 配列
puts [1, 2, 3]

# ハッシュ
puts {'ja' => '81'}

# 変数名 = 式や値
num = 123
puts num

greet = "Hi"
puts greet

is_done = true
puts is_done

n = 10 * 2
puts n

変数名は監修として小文字のスネークケースで書く文化がある。(_)で英単語を区切る。

is_done = true
puts is_done

home_page = "/home"
puts home_page

変数名は英語の小文字、アンダースコア、で始めることができる。

_private = "private"
puts _private

tax_10 = "10%"
puts tax_10

数字から始めるとSyntaxErrorが発生する

1number = 1
puts 1number

error code

basic2/literal.rb:35: syntax error, unexpected local variable or method, expecting end-of-input (SyntaxError)
1number = 1
 ^~~~~~

演算子による値の比較

puts 1 < 2
puts 1 <= 2
puts 1 > 2
puts 1 >= 2
puts 1 == 2
puts 1 == 1
puts 1 != 2

log

true
true
false
false
false
true
true

嘘か本当か?

Rubyにはfalsenilがある。nilだとログが表示されなかった。

puts '--------'
puts true
puts false
puts nil

log

--------
true
false

nilを使った例。nilは、Swift以外であるの忘れていた。Goにもあったような。

# 1. 基本的な nil チェック
def basic_nil_check(data)
    if data.nil?
      puts "データなし"
    else
      puts "データあり: #{data}"
    end
  end
  
  # 2. nil?メソッドを使用した条件分岐
  def nil_method_check(data)
    if !data.nil?
      puts "データあり: #{data}"
    else
      puts "データなし"
    end
  end
  
  # 3. 三項演算子を使用したnil判定
  def ternary_operator_check(data)
    result = data.nil? ? "データなし" : "データあり: #{data}"
    puts result
  end
  
  # 4. ||演算子を使用したデフォルト値の設定
  def or_operator_default(data)
    result = data || "デフォルト値"
    puts "結果: #{result}"
  end
  
  # 5. &.演算子(安全なナビゲーション演算子)を使用
  def safe_navigation_operator(data)
    length = data&.length || 0
    puts "データの長さ: #{length}"
  end
  
  # 6. ||=演算子を使用した初期化
  def conditional_assignment(data)
    data ||= "デフォルト値"
    puts "結果: #{data}"
  end
  
  # サンプルの使用
  some_data = "Hello"
  no_data = nil
  
  basic_nil_check(some_data)  # 出力: データあり: Hello
  basic_nil_check(no_data)    # 出力: データなし
  
  nil_method_check(some_data) # 出力: データあり: Hello
  nil_method_check(no_data)   # 出力: データなし
  
  ternary_operator_check(some_data) # 出力: データあり: Hello
  ternary_operator_check(no_data)   # 出力: データなし
  
  or_operator_default(some_data) # 出力: 結果: Hello
  or_operator_default(no_data)   # 出力: 結果: デフォルト値
  
  safe_navigation_operator(some_data) # 出力: データの長さ: 5
  safe_navigation_operator(no_data)   # 出力: データの長さ: 0
  
  conditional_assignment(some_data) # 出力: 結果: Hello
  conditional_assignment(no_data)   # 出力: 結果: デフォルト値

まとめ

def endのコードはよくみる機会があるので書いて練習した方がいいなと思った。Pythonに似てるから理解はしやすい。

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