Skip to content

Instantly share code, notes, and snippets.

View chiragmongia's full-sized avatar

Chirag Mongia chiragmongia

View GitHub Profile
<html>
<head>
</head>
<body bgcolor="#F2F2F2">
<h1 align="center">HTML form exercise</h1>
<p>
<font color="red">Please note:</font> This Example demonstrates how HTML forms can be used. Submit button should submit the button and reset button should reset the form(revert the changes in form fields). The form layout should be the same as below.
</p>
<b>Contact form</b>
<form action="default.htm" method="post">
# Question- Occurence - Hash
#Count the ocurrences of various alphabet letters in an input string and store it in hash.
def alphabet_count_and_store_in_hash(hash, input_string)
input_string.each_char { |char| hash[ char ] += 1}
hash.delete_if {|k,v| k !~ /^[a-zA-Z]+$/ }
end
# Main
hash = Hash.new(0)
#Question- Reverse Sentence
#Use string methods to reverse the words arrangement in a sentence.
#Eg: "An apple a day keeps the doctor away" -> "away doctor the keeps day a apple An"
def reverse_string (input_string)
input_string.split.reverse!.join(" ")
end
#Main
def factorial(num)
if num > 0
"Factorial is: #{(1..num).inject(:*)}"
else
"Number should be greater than zero"
end
end
p "Factorial Using Ranges"
print "Enter the number: "
#Question- Character Count - Ranges
#Write a method that returns the no of various lowercase, uppercase, digits and special characters used in the string. Make use of Ranges.
def character_count(input_string)
lower, upper, number, special_character = 0, 0, 0, 0
splitted_string = input_string.split(//)
for i in 0...splitted_string.size
case splitted_string[i]
when 'a'..'z'
lower += 1
def palindrome?(input_string)
input_string.reverse == input_string
end
#Main
wish_to_continue = 'a'
while wish_to_continue !~ /\Aq/i
p "Enter the string"
input_string = gets.chomp
if palindrome?(input_string)
#Question - Replace - Regex
#Ask user to enter text. Replace each vowel in the text with a '*' using regular expression.
def replace_vowels_with_asterisk(input_text)
input_text.gsub(/[aeiou]/i, '*')
end
#Main
puts "Replacing Vowels with '*'"
puts "Enter the text"
#Question- Prime Numbers - Step
#Define a method to find all prime numbers upto n using 'step' function.
def prime(num)
prime_no = []
a=0
prime_no << 2
3.step(num,2) do |n|
3.step(n/2,1) do |k|
if n % k == 0
#Quetion- Power - Array
#Define a method power() for an array. It takes an argument 'x' and returns the array with elements raised to power 'x'. Try to make use of array functions.
#Eg: [1,2,3,4,5,6].power(3) -> [1, 8, 27, 64, 125, 216]
class Array
def power(power_value)
self.each { |i| p i ** power_value }
end
end
#Quetion- Power - Array
#Define a method power() for an array. It takes an argument 'x' and returns the array with elements raised to power 'x'. Try to make use of array functions.
#Eg: [1,2,3,4,5,6].power(3) -> [1, 8, 27, 64, 125, 216]
class Array
def power(power_value)
self.each { |i| p i ** power_value }
end
end