DEV Community

aly quey
aly quey

Posted on

Simple Memorization BEYOND

This REPO

From last post,
there's a question. memorization on falsy case.

Thank you @jakebman . :)

I changed code.

clas Smile
  SmileError = Class.new(StandardError)

  attr_accessor :smile

  # @smile is false on initialization.
  def initialize
    @smile = false
  end

  def ensmile(cry: false)
    @smile ||= begin
      puts 'memorize start'
      raise SmileError if cry
      puts 'memorize success'
      "SMILE"
    rescue SmileError
      puts 'memorize fail'
      "CRY"
    end
  end
end

(spec file is same)
Enter fullscreen mode Exit fullscreen mode

And ran rspec

FF

Failures:

  1) Smile#ensmile returns "SMILE"
     Failure/Error: expect(smile.smile).to be_nil

       expected: nil
            got: false
     # ./spec/smile_spec.rb:8:in `block (3 levels) in <top (required)>'

  2) Smile#ensmile returns "CRY"
     Failure/Error: expect(smile.smile).to be_nil

       expected: nil
            got: false
     # ./spec/smile_spec.rb:14:in `block (3 levels) in <top (required)>'

Finished in 0.04088 seconds (files took 0.48848 seconds to load)
2 examples, 2 failures

Failed examples:

rspec ./spec/smile_spec.rb:7 # Smile#ensmile returns "SMILE"
rspec ./spec/smile_spec.rb:13 # Smile#ensmile returns "CRY"
Enter fullscreen mode Exit fullscreen mode

It's okay because of false after initialization.
Just fix spec file.

-------- a/spec/smile_spec.rb
+++ b/spec/smile_spec.rb
@@ -5,13 +5,13 @@ RSpec.describe Smile do
   let(:smile) { described_class.new }
   describe '#ensmile' do
     it 'returns "SMILE"' do
-      expect(smile.smile).to be_nil
+      expect(smile.smile).to be_falsy
       expect(smile.ensmile).to eq 'SMILE'
       expect(smile.smile).to eq 'SMILE'
     end

     it 'returns "CRY"' do
-      expect(smile.smile).to be_nil
+      expect(smile.smile).to be_falsy
       expect(smile.ensmile(cry: true)).to eq 'CRY'
       expect(smile.smile).to eq 'CRY'
     end
Enter fullscreen mode Exit fullscreen mode

Then re-ran rspec.

Finished in 0.00841 seconds (files took 0.4119 seconds to load)
2 examples, 0 failures
Enter fullscreen mode Exit fullscreen mode

Okay. And check on pry.

1) nil
2.4.0 (main):0 > a=nil
=> nil
2.4.0 (main):0 > a ||= 'cat'
=> "cat"
2.4.0 (main):0 > a
=> "cat"

b) false
2.4.0 (main):0 > b=false
=> false
2.4.0 (main):0 > b ||= 'dog'
=> "dog"
2.4.0 (main):0 > b
=> "dog"

3) already set to Object something
2.4.0 (main):0 > r='roo tiger'
=> "roo tiger"
2.4.0 (main):0 > r ||= 'nwo'
=> "roo tiger"
2.4.0 (main):0 > r
=> "roo tiger"
Enter fullscreen mode Exit fullscreen mode

If I'd like to keep false on initialize, it is not working.... 😢

TIL: don't do under falsy condtion and don't do in your home.

Top comments (0)