Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implements the #blocks_counted method #1

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions lib/unicode/blocks.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,22 @@ module Unicode
module Blocks
def self.blocks(string)
res = []
string.each_char{ |char|
string.each_char do |char|
block_name = block(char)
res << block_name unless res.include?(block_name)
}
end
res.sort
end
class << self; alias of blocks; end

def self.blocks_counted(string)
string.each_char.with_object({}) do |char, res|
block_name = block(char)
res[block_name] ||= 0
res[block_name] += 1
end
end

def self.block(char)
require_relative 'blocks/index' unless defined? ::Unicode::Blocks::INDEX
codepoint = char.unpack("U")[0] or raise(ArgumentError, "Unicode::Blocks.block must be given a valid char")
Expand Down
8 changes: 6 additions & 2 deletions spec/unicode_blocks_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,12 @@
assert_equal [], Unicode::Blocks.of("")
end

it "will return all blocks that characters in the string belong to" do
assert_equal ["Basic Latin", "Cyrillic"], Unicode::Blocks.of("СC")
it "will return all unique blocks that characters in the string belong to" do
assert_equal ["Basic Latin", "Cyrillic"], Unicode::Blocks.of("СCСC")
end

it "will count how many characters belong to each matched block" do
assert_equal({"Basic Latin"=>2, "Cyrillic"=>2}, Unicode::Blocks.blocks_counted("СAСA"))
end

it "will return all blocks in sorted order" do
Expand Down