Created
October 29, 2014 14:58
-
-
Save mehdi-farsi/405b4767ee95deb1cb9c to your computer and use it in GitHub Desktop.
Extract and store a value from string using REGEXP
This file contains 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
require 'minitest/autorun' | |
class ExtractAndSortTest < MiniTest::Unit::TestCase | |
def setup | |
@lines = [ | |
'Article 1 -- (45)', | |
'Article 2 -- (42)', | |
'Article 3 -- (62)', | |
'Article 4 -- ()' | |
] | |
end | |
def test_extract_comment_count_from | |
assert_equal(45, extract_comment_count_from('Article 1 -- (45)')) | |
assert_equal(62, extract_comment_count_from('Article 2 -- (62)')) | |
assert_equal(nil, extract_comment_count_from('Article 3 -- ()')) | |
end | |
def test_store_comment_count | |
assert_equal([45, 42, 62], store_comment_counts(@lines)) | |
end | |
def test_sort_comment_counts | |
assert_equal([62, 45, 42], sort_comment_counts(@lines)) | |
end | |
end | |
def extract_comment_count_from(line) | |
match = /\((\d+)\)/.match(line) | |
!match.nil? ? match[1].to_i : nil | |
end | |
def store_comment_counts(lines) | |
comment_counts = [] | |
lines.each do |line| | |
comment_count = extract_comment_count_from(line) | |
(comment_counts << comment_count) unless comment_count.nil? | |
end | |
return comment_counts | |
end | |
def sort_comment_counts(lines) | |
comment_counts = store_comment_counts(lines) | |
comment_counts.sort { |a, b| b <=> a } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment