Write a program to find smallest and longest substring of a string in Ruby
class FindSmallestAndLongestSubstring
def findSmallestAndLongestSubstring
print "Enter the string: "
input_string = gets.chomp
all_substrings = input_string.split(" ")
smallest_string = all_substrings[0]
longest_string = all_substrings[0]
all_substrings.each do |s|
smallest_string = s if smallest_string.length > s.length
longest_string = s if longest_string.length < s.length
end
puts "Smallest substring: #{smallest_string}"
puts "Longest substring: #{longest_string}"
end
end
p = FindSmallestAndLongestSubstring.new
p.findSmallestAndLongestSubstring
Output:
class FindSmallestAndLongestSubstring
def findSmallestAndLongestSubstring
print "Enter the string: "
input_string = gets.chomp
all_substrings = input_string.split(" ")
smallest_string = all_substrings[0]
longest_string = all_substrings[0]
all_substrings.each do |s|
smallest_string = s if smallest_string.length > s.length
longest_string = s if longest_string.length < s.length
end
puts "Smallest substring: #{smallest_string}"
puts "Longest substring: #{longest_string}"
end
end
p = FindSmallestAndLongestSubstring.new
p.findSmallestAndLongestSubstring
Output:
Enter the string: umesh kushwaha best ror developer
Smallest substring: ror
Longest substring: developer
|
p string.split.max_by(&:length)
ReplyDelete