LoginSignup
0
0

More than 5 years have passed since last update.

Hashの値が80以外だったらある処理を実行する、という場合、どの書き方が一番わかりやすいか?

Last updated at Posted at 2012-09-09

個人的にぱっと見て挙動が予想しやすいのは3。
1は何が起こるか分からない。
2も理解するのに時間がかかる。
4は短く書けるけど、書き手の意図がわかりにくい。

require 'rspec'
require 'active_support/core_ext/string'

describe "convert hash value to integer if the value is not '80'" do
  let(:hash) { {to_exclude: '80', to_include1: '8080', to_include2: '3000'} }

  shared_examples_for 'samples' do
    specify { subject.call(:to_include1).should == 8080 }
    specify { subject.call(:to_include2).should == 3000 }
    specify { subject.call(:to_exclude).should be_nil }
    specify { subject.call(:not_defined).should be_nil }
  end

  describe '1. use unless/or' do
    it_should_behave_like 'samples' do
      subject { ->(key) { hash[key].to_i unless hash[key].blank? or hash[key] == '80' } }
    end
  end

  describe '2. use if/not/or' do
    it_should_behave_like 'samples' do
      subject { ->(key) { hash[key].to_i if not(hash[key].blank? or hash[key] == '80') } }
    end
  end

  describe '3. use if/and' do
    it_should_behave_like 'samples' do
      subject { ->(key) { hash[key].to_i if hash[key].present? and hash[key] != '80' } }
    end
  end

  describe '4. use unless/include?' do
    it_should_behave_like 'samples' do
      subject { ->(key) { hash[key].to_i unless [nil, '80'].include? hash[key] } }
    end
  end
end
$ rspec sample_spec.rb
................

Finished in 0.004 seconds
16 examples, 0 failures

え?そもそもこのRSpecがわかりにくい?

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