Ruby: Count Unique Consonants

Using array intersection to count unique consonants.

nick3499
1 min readDec 9, 2018

Interactive Ruby Shell

irb(main):001:0> s = 'dRGgr90xy'
=> "dRGgr90xy"
irb(main):002:0> con = ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"]
=> ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"]
irb(main):003:0> a = s.downcase
=> "drggr90xy"
irb(main):004:0> a = a.split('')
=> ["d", "r", "g", "g", "r", "9", "0", "x", "y"]
irb(main):005:0> (con & a).length
=> 5

In the Ruby REPL demonstration above, unique consonants are found by intersecting an array containing all consonants with a string passed to the function count_consonants(). That string passed to the function is first converted to all lowercase letters, then split into an array containing separate character strings which are finally counted, e.g. 5.

Reference

--

--

nick3499
nick3499

Written by nick3499

coder of JavaScript and Python

No responses yet