LoginSignup
0
1

More than 3 years have passed since last update.

[Ruby] 基本のメソッド一覧(追記中)

Last updated at Posted at 2020-03-03

はじめに

「改定4版 基礎 Ruby on Rails / 黒田努・佐藤和人」を使ってRailsの学習をしています。
この本に出てくるメソッドの忘備録を作っておきたいと思って作成しました。

コードはファイルにコピペしてすぐターミナルで実行できるような形式で書いています。

※ 随時更新&追記していきます。
※ p.はこの本のページナンバーです。

メソッド一覧

p.85
respond_to?()
引数にシンボルを渡すと、そのオブジェクトがメソッドを持っているかどうか調べられる

example.rb
def count_10
    10.times do |i|
        print i, ","
    end
    puts "'count_10' method using 'times' method" if 10.respond_to?(:times)
end
count_10
# output: 0,1,2,3,4,5,6,7,8,9,'count_10' method using 'times' method

p.86
include?()
引数が指定した配列に含まれているかどうか

example.rb
def fruit
    arr = ["apple", "banana", "lemon"]
    puts "'arr'配列は'apple'を含む" if arr.include?("apple")
end 
fruit
# output: 'arr'配列は'apple'を含む

下記のように入力値を受け取り、その値によって条件分岐させることもできる

example.rb
def passphrase
    print "合言葉:"
    word = gets.chomp
    if ["apple", "banana", "lemon"].include?(word)
        puts "OK"
    else
        puts "NO"
    end
end
passphrase
# output: 合言葉:
# 入力値がapple, banana, lemonのどれかだと OK、
# それ以外だと NOが返される

p.87
all?
配列には、ブロック({}←これ)を使って条件を調べるためのメソッドがあり、これは
配列の中の全てが条件を満たすかどうかを調べられる

exaple.rb
def all_zero_or_more
    arr = [0,1,2,3,4,5,6,7,8,9,10]
    puts "OK" if arr.all?{|item| item >= 0}
end
all_zero_or_more
# output: OK

p.87
any?
これもブロックを使って条件を調べるためのメソッド
配列の中のどれかが条件を満たすかどうかを調べられる

exaple.rb
def five_or_more
    arr = [0,1,2,3,4,5,6,7,8,9,10]
    puts "OK" if arr.any?{|item| item >= 5}
end
five_or_more
# output: OK
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