Skip to content

Instantly share code, notes, and snippets.

@sanderDijkxhoorn
Created October 6, 2024 19:10
Show Gist options
  • Save sanderDijkxhoorn/6a66c961abf56a7854f15755ec911ad1 to your computer and use it in GitHub Desktop.
Save sanderDijkxhoorn/6a66c961abf56a7854f15755ec911ad1 to your computer and use it in GitHub Desktop.
Filtering an array in Ruby by character properties
# A simple implementation of character-based filtering in Ruby, covering different edge cases and use scenarios.
def filter_array(input)
# Filter array for numbers
num_array = input.select { |item| item =~ /\d/ }
# Filter array for capitals
capital_array = input.select do |item|
item =~ /^[A-Z]+$/ ? true : false
end.compact
# Filter array for lower case letters only
lower_case_array = input.select { |item| item =~ /^[a-z]+$/ }
# Filter array for only a-z no numbers
alpha_no_num_array = input.select do |item|
item =~ /^[a-zA-Z]+$/ ? true : false
end.compact
# Filter array for arrays with at least one capital letter
mixed_case_array = input.select do |item|
item =~ /[A-Z]/ ? true : false
end.compact
[num_array, capital_array, lower_case_array, alpha_no_num_array, mixed_case_array]
end
input = [
# all numbers
"12345", "67890", "1234567890",
# all capitals
"ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghij", "KOKKOK",
# lower case only
"abcdefghijklmnopqrstuvwxyz", "hello world",
# mix of upper and lower case letters
"AbCdefGhIjKlMnOpQrStUvWxYz", "aBcDeFgHiJkLmNoPqRsTuVwXyZ",
# strings with numbers
"Hello World! 12345", "foo bar 67890", "test string 1234567890",
# strings with special characters
"!@#$%^&*()", "?_+~`[]{}|;:,.<>?/\\", "@#$%$&*()",
# all combinations of uppercase and lowercase letters, digits, and special characters
"AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz!", "12345678901234567890!@#$%^&*()",
# empty strings
"", " ",
# long strings
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()" * 100,
"Hello World! 12345 67890 1234567890!" * 100
]
results = filter_array(input)
puts "Numbers: #{results[0]}"
puts "Capitals: #{results[1]}"
puts "Lower case only: #{results[2]}"
puts "Only a-z no numbers: #{results[3]}"
puts "Arrays with at least one capital letter: #{results[4]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment