Skip to content

Instantly share code, notes, and snippets.

@mehdi-farsi
Created October 29, 2014 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mehdi-farsi/405b4767ee95deb1cb9c to your computer and use it in GitHub Desktop.
Save mehdi-farsi/405b4767ee95deb1cb9c to your computer and use it in GitHub Desktop.
Extract and store a value from string using REGEXP
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