Created
July 26, 2013 19:16
-
-
Save mokevnin/6091475 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def word_count(str) | |
previous = :outside | |
current = :outside | |
count = 0 | |
str.each_char do |char| | |
case current | |
when :outside | |
previous = :outside | |
if char != ' ' | |
current = :inside | |
end | |
when :inside | |
previous = :inside | |
if char == ' ' | |
current = :outside | |
end | |
end | |
#NOTE теперь мы можем фигачить любую логику на любые переходы | |
#при этом кастомная логика полностью отделена от работы самой машины. | |
#Такой подход в том числе позволяет автоматизировать работу с SM и это делает наш гем | |
if previous == :outside && current == :inside | |
count += 1 | |
end | |
end | |
count | |
end | |
require 'minitest/autorun' | |
class TestCase < MiniTest::Test | |
def test_word_count | |
assert_equal 0, word_count('') | |
assert_equal 1, word_count('asdf') | |
assert_equal 2, word_count(' easdf asdf') | |
assert_equal 2, word_count('easdf asdf ') | |
assert_equal 3, word_count(' as asdf asdf ') | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment