Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

書籍 Ruby Cookbook | Predicate Method

パンくず

Ruby Cookbook
Predicate Method

概要

Predicate Method

Predicate Method

Predicate Method=述語メソッド

Rubyでは真偽値を返すメソッド=述語メソッドは末尾に?をつけます

サンプル

puts "".empty? # => true
puts "hoge".empty? # => false

# 自作クラスにPredicate Methodを実装
class Hoge
  attr_accessor:hoge
  def initialize(hoge);@hoge=hoge;end
  def hoge?;@hoge=="hoge";end
end

hoge = Hoge.new("hoge")
puts Hoge.new("hoge").hoge? # => true
puts Hoge.new("hige").hoge? # => false

出力

true
false
true
false