Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 3 years have passed since last update.

ruby 第4回 assert_equal

Last updated at Posted at 2020-11-18

お題: assert_equal

期待値と即値がequalかどうかを確かめる関数 assert_equal を自作する.

解法: red, green

とりあえず例を参考に,

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

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

とすると, p assert_equal(1, 1) は true, p assert_equal(1, 2) は false が返ってきた.

解説: colorize -出色の継承-

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)

とすると, p assert_equal(1, 1) は true (緑), p assert_equal(1, 2) は false (赤) が出力された.

改良: richer output

出力を少し細かく. print の中身を変更.


require 'colorize'

def assert_equal(expected, result)
    if expected == result
	print "succeeded in assert_equal.\n".green
    else
	print "failed in assert_equal.\n".red
    end
end

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

拡張: assert_not_equal

今度は assert_not_equal を自作. 比較を!=に変えるだけ.


require 'colorize'

def assert_not_equal(expected, result)
    if expected != result
	print "succeeded in assert_not_equal.\n".green
    else
	print "failed in assert_not_equal.\n".red
    end
end

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

補足: 重複実行の予防

code が書いてあるファイル名 (FILE) が,動いているファイル名 ($PROGRAM_NAME) と一致したら中身を実行する書き方があるらしい.


require './assert_equal'
require './assert_not_equal'

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

参考サイト

チャート式ruby-IV(assert_equal)


  • source ~/Lecture/Fall2020/M-ScaleSimu/grad_members_20f/members/hiroki0733/c4_assert_equal.org
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?