Skip to content

Instantly share code, notes, and snippets.

@deepakmahakale
Created June 10, 2018 15:53
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 deepakmahakale/af8eef07ff0cf88539938d5663ee1e1f to your computer and use it in GitHub Desktop.
Save deepakmahakale/af8eef07ff0cf88539938d5663ee1e1f to your computer and use it in GitHub Desktop.
StringValidator
class StringValidator
ALLOWED_PARANTHESIS = {
')' => '(',
'}' => '{',
']' => '['
}.freeze
def initialize(value = '')
@text = value
end
def valid?
!@text.empty? && balanced?
end
private
def balanced?
bracket_stack = []
@text.each_char do |char|
if ALLOWED_PARANTHESIS.value?(char)
bracket_stack << char
elsif ALLOWED_PARANTHESIS.key?(char)
return false unless bracket_stack.pop == ALLOWED_PARANTHESIS[char]
else
# has only other matching parenthesis in between
return false
end
end
bracket_stack.empty?
end
end
loop do
puts 'Enter the input string: (type "exit" to leave)'
input = gets.chomp
break if input == 'exit'
string = StringValidator.new(input)
# String just because of the required output is 'True' and 'False'
puts string.valid? ? 'True' : 'False'
end
> ruby validate_string.rb
#=> Enter the input string: (type "exit" to leave)
#=> ()[]{}
#=> True
#=> Enter the input string: (type "exit" to leave)
#=> ([{}])
#=> True
#=> Enter the input string: (type "exit" to leave)
#=> ([]{})
#=> True
#=> Enter the input string: (type "exit" to leave)
#=> ([)]
#=> False
#=> Enter the input string: (type "exit" to leave)
#=> ([]
#=> False
#=> Enter the input string: (type "exit" to leave)
#=> [])
#=> False
#=> Enter the input string: (type "exit" to leave)
#=> ([})
#=> False
#=> Enter the input string: (type "exit" to leave)
#=> exit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment