Usually in shell script we have wonderful text process tools like sed, awk similar options I want to explore in the Ruby scripting. Here we go with small sample where the script will input a text string. then sub is a built-in function in Ruby will replaces the string. The syntax of sub looks like vi command mode replace option.
Snippet:
puts "This program will replace your string"
print "Enter a string: "
user_input = gets.chomp
if user_input.length > 0
user_str = user_input
rplcd_str = user_input.sub(/#{user_str}/,'Voila!')
puts "Your String: #{user_str} Replaced with: "
else
puts "Please enter a valid string!\n"
end
Execution:
ruby test.rb
This program will replace your string
Enter a string: Sunil
Your String: Sunil Replaced with: Voila!
Snippet:
puts "This program will replace your string"
print "Enter a string: "
user_input = gets.chomp
if user_input.length > 0
user_str = user_input
rplcd_str = user_input.sub(/#{user_str}/,'Voila!')
puts "Your String: #{user_str} Replaced with: "
else
puts "Please enter a valid string!\n"
end
ruby test.rb
This program will replace your string
Enter a string: Sunil
Your String: Sunil Replaced with: Voila!