3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Assert&rubular

Last updated at Posted at 2020-12-27

!Mac OS X-10.15.7 !ruby-2.7.1p83

assert_equal

equalかどうかを判定する関数を書いてみる

def assert_equal(expected, result)
  return expected == result
end

p assert_equal(1,1)
p assert_equal(1,2)

実行結果

$ ruby assert_equal.rb
true
false

Colorize

出力に色を付けてみることができる

require 'colorize'

def assert_equal(expected, result)
  if expected == result
    puts 'true'.green
  else
    puts 'false'.red
  end
end

assert_equal(1,1)
assert_equal(1,2)

実行結果

$ ruby assert_equal.rb
true
false

trueが赤色に,falseが緑色に出力される

richな出力

1)引数でとってきた,expectedとresultの値を表示する
2)true、false時のメッセージを出す
を実現する

require 'colorize'
require 'colorize'

def assert_equal(expected, result)
  puts "expected: #{expected}"
  puts "result: #{result}"
  if expected == result
    puts "succeeded in #{__method__}.\n".green
  else
    puts "failed in #{__method__}.\n".red
  end
end

assert_equal(1, 1)
assert_equal(1, 2)

関数の整理

重複している処理は整理

require 'colorize'

def assert_data_print(expected, result)
  puts "expected: #{expected}"
  puts "result: #{result}"
end

def assert_result_print(is_success, method_name)
  if is_success
    puts "succeeded in #{method_name}.\n".green
  else
    puts "failed in #{method_name}.\n".red
  end
end

def assert_equal(expected, result)
  assert_data_print(expected, result)
  assert_result_print(expected == result, __method__)
end


def assert_not_equal(expected, result)
  assert_data_print(expected, result)
  assert_result_print(expected != result, __method__)
end

assert_equal(1, 1)
assert_equal(1, 2)
assert_not_equal(1, 1)
assert_not_equal(1, 2)

重複実行の予防

if $PROGRAM_NAME == __FILE__
  assert_equal(1, 1)
  assert_equal(1, 2)
  assert_not_equal(1, 2)
  assert_not_equal(1, 1)
end

のようにする
codeが書いてあるファイル名(FILE)が,動いているファイル名($PROGRAM_NAME)と一致するかを確認することで、requireの時はこの中身が実行されないようにできる

Rubular

文字情報を取り出す便利ツールな正規表現


  • source ~/grad_members_20f/members/wjswnsrud12/memo9.org
3
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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?