What is Ruby:-
Ruby is a pure object-oriented programming language that is used to create desktop and web applications.
ruby language is easy to learn and contain various predefine library to implement program logic.
ruby is open source programming language, all software packages, tools, and frameworks are freely available, we can download ruby software and use in the program.
..........................................................................
Ruby Syntax:-
Ruby programming language can be written into three different patterns.
1) Paragraph pattern:-
we will write a collection of statements similar to paragraphs.
puts("hello world")
puts("welcome")
2) Procedural pattern:-
We will create a separate function to define the program, it provides a structured pattern to write the Ruby code.
def methodname()
statements
statements
end
call
methodname()
3) OOPS Pattern:-
using this pattern we will create a class and object then define program code.
class Classname
def methodname()
end
end
obj = Classname.new
obj.methodname()
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
Ruby History:-
Ruby was created by Matz (Yukihiro Matsumoto) in 1990. it is influenced by C and shell script language. Ruby was released into the industry in 1993.
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
Ruby Features:-
1) Open source script
2) Best in performance & Security
3) Simple Syntax Structure
4) Rich library to define in-built functionality
5) Distributed
6) Operating System Independent
7) Multithreading support
8) fully supported by oops
......................................................................
What is Rails?
It is the MVC-based web framework that is used to create a dynamic web application.
Rails framework is completely based on CLI(Command-line interface).
MVC means Model, View, and Controller, it is used to distribute the project on different project layers.
The model is used to create the data access layer, the view is used to create the user access layer, and the controller is used to create business code and work as an Intermediate between Model and View.
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
Ruby Operator?
The operator is used to perform the operation using operand, ruby not support increment and decrement operators.
1) Arithmetic Operator:-
+ , -, *, **,/
2) Conditional Operator or Relational Operator:-
<,>,<=,>=,!=
3) Assignment Operator:-
3.1) Simple Assignment =
3.2) Complex Assignment
+=, -=,*=,/=,%=,**=
4) Comparision Operator:-
== to compare integer value or value type data type, eql it is used to compare object type data
5) Logical operator
&& it will return true when all condition is true
|| it will return true when only one condition is true
! opposite of true and false
6) Ternary operator:-
It will solve the condition-based problem using a single-line statement.
(condition)?true:false
Conditional Statement in ruby:-
It is used to solve the condition-based problem using if, elsif, else statements, ruby also provide unless--else statement and case statement to solve the program.
1) if condition then
statement
end
2) if condition then
statement
else
statement
end
3) Ladder if Else or Elsif
if condition then
statement
elsif condition then
statement
else
statement
4) case option
when optionvalue then
statement
when optionvalue then
statement
...
else
statement
end
WAP to check vowels and consonants using case statements?
Soution:-
Loop Statements in ruby:-
It is used to solve range-based problems using common repeatable statements, the loop will continuously be executed until the condition is false.
Loop is also called an iterative statement in a ruby programming language.
Loop uses three statements to execute the loop
Forward Backward
1) init i=min i=max
2) condition i<=max i>=min
3) iteration i=i+1 i=i-1
Type of loop:-
1) While:-
It provides an entry-level-based iterative statement, which means first checking the condition then executing the statement.
Syntax
init
while conditioning then
statement
increment
Example of while loop:-
WAP to calculate factorial of any entered number?
ASSIGNMENTS?
Q) WAP to print 1 to 5 and 5 to 1 using a single while loop?
Q) WAP to calculate square and cube of one digit positive number?
Q)WAP to print 1 to 5 and 5 to 1 again 1 to 5 and 5 to 1 using a single while loop?
Q)WAP to perform the addition of a one-digit positive number?
Q) WAP to check the prime number?
Q)WAP to reverse any digit number?
Q) WAP to find max digit, second max digit in mobile number?
2) do. while:- First execute statement then check condition, it is also called exit control loop
loop do
statement
if condition
break
end
increment|decrement
end
Example of do-while
3) until:- It is the opposite of the while loop, it will execute until the condition will be true.
init
until condition
statement
increment
end
WAP to print table using until--end?
4) for:- It is used to provide simple syntax structure as compared to while, do-while and it'll because it will contain all components of a loop under a single line statement using range operator.
for I in start..end
statement
end
Example of for loop using ...
Example of for loop using .. operator?
Nested For Loop:-
We will write more than one for loop using the combination of the outer for loop and inner for loop, outer for loop will execute once after the inner for loop will execute till last, when the inner for loop condition will be false then the outer for loop will increase. and when the outer for loop condition is false then the loop will terminate.
for I in start..end
for j In start..end
print("data")
puts()
Example of Nested For Loop:-
Another Loop Example:-
Print Following Pattern:-
A B C D E
A B C D
A B C
A B
A
.............................................................
A
A B
A B C
A B C D
A B C D E
.....................................
I j
1 1
2 2
3 3
4 4
5 5
for i in range(1,6):
for j in range(1,7-i):
Assignment of Nested For Loop In Python:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
............................................
A B C D E
a b c d
A B C
a b
A
..........................................................
A a B b C
A a B b
A a B
A a
A
.........................................................
1 2 3 4 5
5 4 3 2
1 2 3
5 4
1
......................................................................
1 0 0 1 0
1 0 0 1
1 0 0
1 0
1
...............................................................................
Create a Pattern to print this pattern:-
A B C D E
B C D E
C D E
D E
E
1) When an application will be loaded then ask for the pin code, if the pin code is correct then the process to the next phase otherwise ask pin code three times if it will be wrong then the application will be closed automatically.
2) If the pin code is correct then ask for operation using the menu Press C for Credit, D for Debit, B for check balance, E for the exit, R for a Repeat operation.
3) If the user performs three operations then automatically exit from the application.
4) Display all log means the internal process
What is Array?
The array is a collection of different types of elements using index=>value pair, the array is a special type of variable that can store multiple values in a single memory address.
Ruby array is dynamic in length means we can increase o decrease the size of the array dynamically.
Syntax of Array
x = Array,new(size,values)
or
x = []
or
x = [item1,item2,item3]
Example of Array:-
Multidimensional Array:-
using this we can store elements based on rows and columns.
Syntax
arrayname = [[rows],[rows]]
Exmple of multidimensional array?
A multidimensional array with different number of row elements:-
Array Assignments:-
1) WAP to sort the elements of the array in ascending order?
3) WAP to merge two arrays in one array?
2 3 4 5 7 11 11 2 5 o/p 3 4 7
6) WAP to display prime elements in the array?
User define function in ruby:-
using this we can categorised the program code under individual named block that can be reused and provide better structure to complex code.
It is also called method approach in the Ruby language.
Syntax of method
def methodname()
end
methodname()
Example:-
Type of Method in ruby:-
1) Default:-
We can provide input and output operations under the method body.
1.1) With return type:-
We can return the output from the function body that can be displayed under the calling function.
def functionname()
return data
end
var = functionname()
print(var)
1.2) Without return type: We can not return any data using without a return type, output will be defined under the function body.
def functionname()
print(statement)
end
functionname()
2) Parametrised:-
We can define an argument under the function parameter that will be called from calling function to called function.
def methodname(param1,param2)
Statement
end
methodname(value1,value2)
type of parametrised function:-
1.1) With return type:-
We can return the output from the function body that can be displayed under the calling function.
def functionname(arg1,arg2)
return data
end
var = functionname(arg1,arg2)
print(var)
1.2) Without return type: We can not return any data using without a return type, output will be defined under the function body.
def functionname(arg1,arg2)
print(statement)
end
functionname()
What is the default argument value?
in the ruby method, we can set the default value under the parameter, if we did not pass the parameter then the default value will be applied.
def functionname(a=10,b=20)
print(a+b)
end
functionname() #30
functionname(1,2) #3
How to return multiple values under parameter?
def functionname(a=10,b=20)
return a,b
end
r = functionname())
Pass variable-length parameters:-
we can pass nth number parameters in ruby method
def functionname(*a)
print(a)
end
functionname(10,20,30)
Assignment of function
Assignment of default function:-
2) Create an ATM Program using a parametrized function?
Another Example:-
Write data to take input from user's?
Rename and Delete the file:-
String Example in ruby:-
String is a collection of char using proper sequence, string indexing is similar to an array, String can be declared using '', "" both in ruby.
ruby provides String interpolation to write variables under String Literals.
Syntax of String
String as a reference
s = "hello"
String as a Object
s = String.new("hello")
Note:- String object is immutable because we can not change the value from the actual address.
How to iterate String object data?
WAP to print only vowel in String?
Operation on String
1) String extraction:-
We can split the String elements using String index.
s = "hello"
print(s[1,3]) #ell
2) String Interpolation:-
We can print variables or manage expressions using #{} which is called String interpolation.
a=10
b=20
s = "a= #{a} and b=#{b} and result = #{a+b}"
print(s)
Assignments of String:-
String-based Program
1) Count total vowel and consonant in String?
2) WAP to reverse String?
3) Convert upper case to lower case?
4) Count total numeric char in String?
5) WAP to convert string elements in the opposite case?
6) WAP to validate email?
7) WAP to validate internet URL it can be HTTP, HTTP, and without HTTP?
8) WAP to check password strength, if it contains consecutive char, without any 3 special char, their name or last name then the password will be weak, if the password contains 3 special char, nonconductive char then the password will be strong?
5) WAP to display the largest palindromic in a string?
6) WAP to find total prepositions in a paragraph
Program to calculate SI using P, R, and T?
OOPS Program:-
What is an object?
It is a real-world entity, which contains identity state and behavior. we can create user define objects which contain memory address as an identity, memory space as a state, and contain and access functionality as a member function.
address = Classname. new
new is used to create memory space.
Component of class:-
1) Data member and member function:-
It is used to define the attribute of the object, the data member will be declared as a variable and the member function will be declared as a method.
type of member function:-
1) class type member function:-
this member function contains a single memory space to store data, it is also called a static member function and it will be defined by self keyword.
Syntax of Class type:-
class Classname:
def self. display
statements
end
end
Classname.display
Example of Class type:-
2) instance type member function
This member function contains separate memory space to fo each object it contains dynamic memory space, In most cases, we prefer a dynamic member function.
class Classname:
def functionname()
statements
end
end
obj = Classname.new()
obj.functionname()
Exampe of Instance type:-
Type of data member:-
According to scope:-
global variable:- this type of variable will be declared globally means we can declare it above class also.
$var=10
class Classname
def methodname()
puts($var)
end
end
Example:-
local variable:-
if we declare a variable under the method block then its scope will be limited means it can not access outside of the method body.
According to memory:-
1) Class type variable or Static Variable @@:-
if we want to create single memory to variable incomplete program then we can declare it a class type variable.
It stores data under class memory, we can not re-allocate memory to class type variable.
note:- if we want to create a shared variable then we can create a class type variable.
2) Instance type variable or dynamic variable @:-
This type of variable memory allocation will be managed by the object, it can store data into individual memory according to each object.
Initializers or init method or constructor:-
It is used to initialize the dynamic data member of the class, the initializers block will be called when we create the object.
type of initializer block:-
1) default initializer:-
this block will be created implicitly if we want to manually create then it is not created implicitly. it is used to initialize the instance data member value.
2) param initializer:- we can pass the parameter value under the object to call parametrized initializer. in ruby, we can define only one initializer underclass
Data abstraction and Data encapsulation:-
Data abstraction means hiding the non-essential details and showing essential details in the program. Data encapsulation means binding the data member or variable under a member function or property is called data encapsulation.
How to implement data abstraction?
Ruby provides an access specifier to implement data abstraction.
1) public: it can be accessed outside of the class then we can create public
2) protected:- it can be accessed outside of the related class means base class to child class
3) private:- it can not be accessed outside of the class then we can create private
Example:-
Data abstraction and Encapsulation:-
Data Encapsulation using getter and setter
Ruby provide an accessor method to provide a mode for data member of the class to read and write data.
1) attr_reader:- only for the read.
2) attr_writer:- only for write.
3) attr_accessor:- read and write both.
Example of attr_reader:-
Example of attr_writer
Example of accessor method:-
Polymorphism:-
..........
Poly means many and morphism means forms using this we can create the same name method and operator that can be used in multiple functionalities.
Ruby supports operation loading and functions overriding concepts under polymorphism.
What is operator overloading?
we can define a single operator under multiple forms uisng operator overloading. we can overload + operator for addition as well as other operation.
Example of operator overloading:-
Inheritance:- it means reusability, using this we can acquire the functionality of parent class to the child class.
Type of Inheritance:-
1) Single Inheritance:-
We can access the features of the base class to the derived class.
class A
end
class B < A
end
Example of Single Inheritance:-
2) Multilevel Inheritance:-
We can access the features of the base class to the derived class and derived class to sub derived class.
class A
end
class B < A
end
class C < B
end
Example of Multilevel Inheritance:-
Hierarchical Inheritance:-
It will provide an inheritance structure from one base class to multiple derived classes using a tree structure. one parent class contains multiple children where a parent will be the root node and the child will be sub-node.
Multiple Inheritance:-
In this inheritance, two base classes features will be combined into a single child class, it is used to inherit the features of multiple classes into a single class but ruby does not support multiple inheritances because ruby has no principle to solve ambiguity problem.
Super() in ruby:-
using this we can call the parent class method to the child class:-
Exception Handling Program in ruby?
It is used to handle unexpected runtime errors in programs. the exception is used to protect the program from interruption.
ruby provide "rescue" and "ensure" and else block to execute statements
Syntax 1st
begin
code section
rescue
error message
end
Example
2) Syntax 2nd:-
begin
code section
rescue
error message
ensure
default statements
end
Syntax 3rd:-
begin
code section
rescue
error message
else
if no any exception
ensure
default statements
end
Example
retry statements:-
it is used to execute throw the cursor into the beginning block. it should be implemented under the rescue block.
Raise:-
it is used to manually call the exception.
User Define Exception:-
using this we can create and call our own exception classes.
What is Thread?
Thread is a collection of lightweight processes, it is used to execute the program parallel. we can use a single thread and multithread both in ruby.
in a programming language, we prefer multithreading concepts for thread implementation.
using multithreading we can execute more than one process parallel under a multicore processor.
How to implement thread in the ruby program?
We create the object of thread class to implement thread
ref = Thread. new{statements}
How to start thread
ref. join()
How to sleep Thread
sleep(timeinterval)
Example of multithreading:-
Thread Synchronization`
Solve these programs in ruby language to improve your logical skills?
WAP to calculate the difference between two dates in the year, the date should be assigned on DDMMYYYY
WAP to Reverse Five Digit Number without using Loop?
WAP to Calculate Addition of Complex Number?
WAP to calculate Simple Interest where rate and time will be constant and the principal will be an integer?
WAP to calculate the area of a triangle, circle, and rectangle in the same program where the value of pi, the base of the triangle, and the height of the rectangle will be constant.
WAP to convert temperature from Celsius to Fahrenheit?
# WAP to check divisibility of the number that it is divisible by 3 and 5 or not?
ReplyDeleteprint "Enter any number: "
num = gets.to_i
if num%3 == 0 && num%5 == 0
puts "the number is divisible by 3 and 5"
elsif num%3 == 0
puts "the number is divisible by 3"
elsif num%5 == 0
puts "the number is divisible by 5"
else
puts "the number is not divisible by 3 and 5"
end
# WAP to check divisibility of the number that it is divisible by 3 and 5 or not? using ternary operator
ReplyDeleteprint "Enter any number: "
num = gets.to_i
cal = num%3 == 0 ? "number is divisible by 3" : num%5 == 0 ? "number is divisible by 5" : num%3 == 0 && num%5 == 0 ? "number is divisible by 3 and 5" : "not divisible 3 and 5"
puts cal
# WAP to check divisibility of the number that it is divisible by 3 and 5 or not?
ReplyDeleteprint "Enter any number: "
num = gets.to_i
if num%3 == 0 && num%5 == 0
puts "the number is divisible by 3 and 5"
elsif num%3 == 0
puts "the number is divisible by 3"
elsif num%5 == 0
puts "the number is divisible by 5"
else
puts "the number is not divisible by 3 and 5"
end
# WAP to check vowel and consonant using a ternary operator?
ReplyDeleteprint "Enter year: "
year = gets.to_i
cal = year%400 == 0 || year%4 == 0 && year%100!=0 ? "Leap year" : "Not Leap year"
puts cal
# range way calculate leap year
ReplyDeleteprint ("Enter starting year: ")
s_year = gets.to_i
print ("Enter ending year: ")
e_year = gets.to_i
for year in s_year..e_year do
if year%400 == 0
puts "#{year} leap year"
elsif year%4 == 0 && year%100 != 0
puts "#{year} leap year"
else
puts "#{year} Not a leap year"
end
end
# WAP to find max digit, second max digit in mobile number?
ReplyDeleteprint "Enter mobile number: "
num = gets.to_i
m = 0
sm = 0
while num!=0
a = num%10
num = num/10
if m < a
sm = m
m = a
elsif sm < a && num!=m
sm = a
end
end
puts "max number is: #{m}"
puts "second max number is: #{sm}"
# WAP to find max digit, second max and third max digit in mobile number?
ReplyDeleteprint "Enter mobile number: "
num = gets.to_i
m = 0
sm = 0
tm = 0
while num!=0
mob = num%10
if m < mob
tm = sm
sm = m
m = mob
elsif sm < mob
tm = sm
sm = mob
elsif tm < mob
tm = mob
end
num = num/10
end
puts "max number is: #{m}"
puts "second max number is: #{sm}"
puts "third max number is: #{tm}"
# WAP to calculate Simple Interest where rate and time will be constant and the principal will be an integer?
ReplyDeleteprint "Enter Principal: "
prn = gets.to_i
print "Enter Rate: "
rate = gets.to_f
print "Enter Time: "
time = gets.to_f
simpleinterest = (prn * rate * time)/100
puts ("Simple Interest is: #{simpleinterest}")
# WAP to display the subject mark of the student which will be entered by the user's if the entered subject mark is eligible for grace then display mark including grace mark otherwise actual mark will display.
ReplyDeleteprint "Enter subject marks: "
sub = gets.to_i
if sub>=28 && sub<33
grace = 33-sub
puts "need of marks: #{grace}"
sub += grace
puts "my actual marks with grace: #{sub}"
else
puts "my actual marks without grace: #{sub}"
end
# user input swap value
ReplyDeleteprint "Enter a value: "
a = gets.to_i
print "Enter b value: "
b = gets.to_i
z = a
a = b
b = z
puts "a value: #{a}"
puts "b value: #{b}"
# swap value using third variable
ReplyDeletea = 10
b = 20
# start swapping
z = a
a = b
b = z
puts "a value: #{a}"
puts "b value: #{b}"
# swap value without using third variable
ReplyDeleteprint "Enter a value: "
a = gets.to_i
print "Enter b value: "
b = gets.to_i
a = a + b
b = a - b
a = a - b
puts "a value: #{a}"
puts "b value: #{b}"
# WAP to display "YES" and "NO" when the user press 'y' and 'n'?
ReplyDeleteprint "Enter n/y: "
num = gets.chomp()
if num == "y"
puts "YES"
elsif num == "n"
puts "NO"
else
puts "invalid"
end
# WAP to check vowel and consonant using a ternary operator?
ReplyDeleteprint "Enter char: "
char = gets.chomp()
cal = char == "a" || char == "e" || char == "i" || char == "o" || char == "u" ? "vowel" : "consonent"
puts cal
# WAP to check that salary is in income tax or not display the total amount and the taxable amount
ReplyDeleteprint "Enter your amount: "
num = gets.to_i
sal = 50000
tax = num-sal
s = num<=sal ? "not taxable, total amount is: #{num}" : "taxable amount is: #{tax}, total amount is: #{tax+sal} "
puts s
# convert km to meter
ReplyDeleteprint "Enter km: "
km = gets.to_f
meter = (km * 1000).to_f
puts "convert km to meter: #{meter}m"
# convert meter to km
ReplyDeleteprint "Enter meter: "
meter = gets.to_f
km = (meter / 1000).to_f
puts "convert meter to km: #{km}km"
# true and false using ternary operator
ReplyDeleteprint "Enter a value: "
a = gets.to_i
puts a<=20 ? true : false
# wap to calculate factorial of any entered number?
ReplyDeleteprint "Enter factorial number: "
num = gets.to_i
fact = 1
if num == 0
puts "invalid!, could not find the factorial of one"
else
i = 1
while i<=num
fact = fact*i
i = i+1
puts "The factorial number #{num} is: #{fact}"
end
end
# feet to inch
ReplyDeleteprint "Enter feet: "
feet = gets.to_f
inch = 12 * feet
puts "convert feet into inch: #{inch}"
# inch to feet
ReplyDeleteprint "Enter inch: "
inch = gets.to_f
feet = inch / 12
puts "Convert into into feet: #{feet}"
print "Temperature value in degree Celsius: "
ReplyDeletecelsius = gets.to_f
Fahrenheit = (celsius * 1.8)+32
puts "The #{celsius} degree Celsius is equal" +
" to: #{Fahrenheit} Fahrenheit"
# 1 way to check vowel and consonent using case statement
ReplyDeleteprint "Enter Char: "
char = gets.chomp()
case char
when "a"
puts "vowel1"
when "e"
puts "vowel2"
when "i"
puts "vowel3"
when "o"
puts "vowel4"
when "u"
puts "vowel5"
else
puts "consonent"
end
# area of triangle
ReplyDeleteprint "Enter a: "
a = gets.to_f
print "Enter b: "
b = gets.to_f
print "Enter c: "
c = gets.to_f
s = (a+b+c)/2
area = (s*(s-a)*(s-b)*(s-c))**0.5
puts "the area of triangle #{area}"
# area of rectangle
ReplyDeleteprint "Enter height: "
height = gets.to_f
print "Enter width: "
width = gets.to_f
area = height*width
puts "the area of rectangle: #{area}"
# area of circle
ReplyDeletePI = 3.14
print "Enter radius of a circle: "
r = gets.to_f
area = PI * r * r
puts "the area of rectangle: #{area}"
# addition of complex number
ReplyDeletea = Complex(6+7i)
b = Complex(7+8i)
sum = a+b
puts "Addition of complex number is: #{sum}"
# add two number without using + operator
ReplyDeleteprint "Enter first number: "
a = gets.to_i
print "Enter second number: "
b = gets.to_i
sum = a-(-b)
puts "add two number: #{sum}"
# WAP to calculate electricity bill where unit price, total consumption will be entered by the user, if the bill is <400 then pay only 100 RS and above this 50% amount will be paid using ternary operator
ReplyDeleteprint "Enter Unit price per unit: "
a = gets.chomp().to_i
print "Enter starting unit: "
from = gets.chomp().to_i
print "Enter ending unit: "
to = gets.chomp().to_i
consumption = to - from
total = a*consumption
puts "Electricity bill from #{from} to #{to}: #{consumption}"
cal = total<400 ? "pay only 100rs" : "pay actual bill with 50% discount: #{total/2}"
puts cal
# WAP to calculate electricity bill where unit price, total consumption will be entered by the user, if the bill is <400 then pay only 100 RS and above this 50% amount will be paid.
ReplyDeleteprint "Enter Unit price per unit: "
a = gets.chomp().to_i
print "Enter starting unit: "
from = gets.chomp().to_i
print "Enter ending unit: "
to = gets.chomp().to_i
cal = to - from
total = a * cal
puts "Electricity bill from #{from} to #{to}: #{cal}"
if total<400
puts "pay only 100rs"
else
puts "pay actual bill with 50% discount: #{total/2}"
end
# divisible 3 and 5 using until loop
ReplyDeleteprint "Enter number: "
num = gets.to_i
x = 1
until x >= num
if x%3 == 0 && x%5 == 0
puts "#{x} is divisible by 3 and 5"
elsif x%3 == 0
puts "#{x} is divisible by 3"
elsif x%5 == 0
puts "#{x} is divisible by 5"
else
puts "#{x} is not divisible by 3 and 5"
end
x += 1
end
# table print using until loop
ReplyDeleteprint "enter any number: "
num = gets.to_i
x = 1
until x >= 11
t = num*x
puts t
x += 1
end
# WAP to print 1 to 5 and 5 to 1 again 1 to 5 and 5 to 1 using a until loop?
ReplyDeletey = 1
until y >= 21
if y <= 5
puts y
elsif y <= 10
puts (11 - y)
elsif y <=15
puts (y - 10)
else
puts (21 - y)
end
y += 1
end
# any number increment decrment using until loop
ReplyDeleteprint "Enter any number: "
num = gets.to_i
x = 1
until x > num
if x <= 5
puts x
else
puts (num + 1- x)
end
x += 1
end
# user input check even odd using while loop
ReplyDeleteprint "Enter number: "
num = gets.to_i
z = 0
while z <= num
if z.even?
puts "#{z} is even"
else
puts "#{z} is odd"
end
z += 1
end
# WAP to check divisibility of numbers from 3,5 with all combinations using for loop
ReplyDeleteprint "Enter starting number: "
num1 = gets.to_i
print "Enter ending number: "
num2 = gets.to_i
for x in num1..num2
if x%3 == 0 && x%5 == 0
puts "#{x} is divisible by 3 and 5"
elsif x%3 == 0
puts "#{x} is divisible by 3"
elsif x%5 == 0
puts "#{x} is divisible by 5"
else
puts "#{x} is not divisible by 3 and 5"
end
end
# using for loop next and break
ReplyDeletefor x in 1..10
if x == 5
next
end
if x == 8
break
end
print x, " "
end
puts
# positive or negative ternary operator
ReplyDeleteprint "Enter number: "
num = gets.to_i
sum = num>=0 ? "positive" : "negative"
puts sum
#WAP to Check Leap Year.
ReplyDeleteputs "enter year"
year=gets().to_i
if year%4==0 && year%100!=0 || year%400==0
puts "leap year"
else
puts "not leap year"
end
# WAP to check number is positive or negative?
ReplyDeleteputs "enter number"
num=gets().to_i
if num>0
puts "this is positive number"
else
puts "this is negative number"
end
WAP to check the greatest number?
ReplyDeletea=10
b=20
c=34
d=23
if a>b && a>c && a>d
puts "a is greatest"
elsif b>c && b>d
puts "b is greatest"
elsif c>d
puts "c is greatest"
else
puts "d is greatest"
end
WAP to check greatest using four different numbers?
ReplyDeletea=10
b=20
c=34
d=23
if a>b && a>c && a>d
puts "a is greatest"
elsif b>c && b>d
puts "b is greatest"
elsif c>d
puts "c is greatest"
else
puts "d is greatest"
end
WAP to check that entered number is one digit negative number or a positive number?
ReplyDeleteputs "enter number"
num=gets().to_i
if num>0 && num<=9
puts "this is one digit number"
else
puts "this is two digit number"
end
WAP to check divisibility of number from 3,5 and 7 with all combination:-
ReplyDeleteputs "enter num"
num=gets().to_i
if num%3==0
puts "num is divisile by 3"
elsif num%5==0
puts "num is divisile by 5"
elsif num%7==0
puts "num is divisile by 7"
else
puts "this is not by anyone"
end
WAP to display "YES" and "NO" when the user press 'y' and 'n'?
ReplyDeleteputs "enter char"
char=gets().chomp
if char=='y'
puts "yes"
elsif char=='n'
puts "no"
else
puts "this is not yes or no"
end
WAP to check that entered char is vowel and consonant without using or operator?
ReplyDeleteputs "enter char"
char=gets().chomp
if char=='a'
puts "this is vowel"
elsif char=='b'
puts "this is vowel"
elsif char=='c'
puts "this is vowel"
elsif char=='d'
puts "this is vowel"
elsif char=='e'
puts "this is vowel"
else
puts "this is consonent"
end
WAP to check that salary is in income tax criteria or not. if in income tax then display income tax slab.
ReplyDeleteputs "enter salary"
salary=gets().to_i
if salary<250000
puts "tax is not payable"
else
puts "tax is payable"
end
WAP TO CHECK THAT USERNAME AND PASSWORD BOTH ARE CORRECT OR NOT WHERE USERNAME IS YOUR FIRST NAME AND PASSWORD YOUR LASTNAME?
ReplyDeleteputs "enter first name"
fname=gets().chomp
puts "enter last name"
lname=gets().chomp
if fname=='abhi' && lname=='kumar'
puts "valid username or password"
else
puts "invalid username or password"
end
# WAP to check the greater number using Ternary Operator?
ReplyDeleteputs "enter first number"
a=gets().to_i
puts "enter second number"
b=gets().to_i
res = a>b ? "a is greater " : "b is greater"
puts res
#WAP to check that salary is in income tax or not display the total amount and the taxable amount
ReplyDeleteputs "enter your salary"
salary=gets().to_i
res = salary<=250000 ? "tax is not payable" : "tax is payable"
puts res
#WAP to check divisibility of number that it is divisible by 3 and 5 or not?
ReplyDeleteputs "enter the number"
num = gets.to_i
res = num%3==0 && num%5==0 ? "num is divisible" : "num is not divisible"
puts res
#WAP to check vowel and consonant using a ternary operator?
ReplyDeleteputs "enter the char"
s=gets().chomp
res= s=='a' || s=='e' || s=='i' || s=='o' || s=='u' ? "this is vowel" : "this is consonent"
puts res
#WAP to check leap year using a ternary operator in ruby?
ReplyDeleteputs "enter the year"
year=gets().to_i
s = year%4==0 && year%100!=0 || year%400==0 ? "leap year" : "not leap year"
puts s
#WAP to check divisibility of number that it is divisible by 3 and 5 or not?
ReplyDeleteputs "enter the number"
num=gets().to_i
res = num%3==0 ? "this is divisible by num" : "this is not divisible by num" && num%5==0 ? "this is divisible by num" : "this is not divisible by num "
puts res
# marksheet calculate program
ReplyDeleteprint "Enter math marks: "
m = gets.to_i
print "Enter physics marks: "
py = gets.to_i
print "Enter science marks: "
s = gets.to_i
print "Enter hindi marks: "
h = gets.to_i
print "Enter english marks: "
e = gets.to_i
# all sub should be 0 to 100 marks
if (m >= 0 && m <= 100) && (py >= 0 && py <= 100) && (s >= 0 && s <= 100) && (h >= 0 && h <= 100) && (e >= 0 && e <= 100)
# all sub should >33 marks if one sub marks is <33 and >28 stu is suppli then so other all sub add bonus then student will be pass
sub = ''
grace = 0
if m < 33
sub += 'Math '
grace = m
end
if py < 33
sub += 'Pysics '
grace = py
end
if s < 33
sub += 'Science '
grace = s
end
if h < 33
sub += 'Hindi '
grace = h
end
if e < 33
sub += 'English '
grace = e
end
# distinction subject
dist = ''
if m >= 75
dist += "Math "
end
if py >= 75
dist += "Physics "
end
if s >= 75
dist += "Science "
end
if h >= 75
dist += "Hindi "
end
if e >= 75
dist += "English "
end
# percentage and grace marks calculate
if grace>=28 && grace <= 33
cal = 33-grace
grace += cal
per = ((m+py+s+h+e+cal)/5).to_f
puts "Supplementary in #{sub} Subject, form #{cal} number then" +
" add bonus so, student will be #{grace} marks."
elsif m >= 33 && s>= 33 && py >= 33 && h >= 33 && e >=33
per = ((m+py+s+h+e)/5).to_f
else
puts "Fail in #{sub} Subject."
exit
end
# division calculate
if per < 33
puts %{Pass in third division #{per}% and Distinction subject #{dist}.} # no need of single and double quotes 1 way
elsif per < 50
puts %Q{Pass in second division #{per}% and Distinction subject #{dist}.} # 2 way
else
puts %{Pass in first division #{per}% and Distinction subject #{dist}.}
end
else
puts %{All sub should be 0 to 100 marks}
end
# WAP to mange ATM operation in simple logic
ReplyDeleteputs "Add to card"
i = 1
while i<=3
print "Enter 4-digit pin no "
pin = gets.to_i
pin1 = 2022
if pin == pin1
puts "correct your pin no"
bal = 500
i = 0
while i<2
puts "Press menu Button"
puts "="*30
puts "C for Credit\tB for check balance\nD for Debit\tR for Repeat operation\nE for the exit"
press = gets.chomp()
if press == "c"
puts "Enter amount"
am = gets.to_i
puts "your total amount #{bal+am}"
elsif press == 'b'
puts "your total amount #{bal}"
elsif press == 'd'
puts "Enter withdraw amount"
am1 = gets.to_i
puts "your remaining amount #{bal-am1}"
elsif press == 'r'
puts "Repeat operation"
elsif press == 'e'
break
else
puts "invalid input"
end
end
break
else
puts "Invalid pin no!, try again[y/n] "
try = gets.chomp()
if try == "y"
end
if try == 'n'
puts "Thanks for using atm"
break
end
end
i += 1
if i == 4
puts "Sorry! only three times using PIN!"
exit
end
end
# nested_for_loop
ReplyDelete#12345
#12345
#12345
#12345
#12345
for x in 1..5
for y in 1..5
print y
end
puts
end
puts
#54321
ReplyDelete#54321
#54321
#54321
#54321
for x in 1..5
for y in 5.downto(1)
print y
end
puts
end
puts
#11111
ReplyDelete#22222
#33333
#44444
#55555
for x in 1..5
for y in 1..5
print x
end
puts ()
end
puts
55555
ReplyDelete44444
33333
22222
11111
for x in 5.downto(1)
for y in 5.downto(1)
print x
end
puts ()
end
puts
2 3 4 5
ReplyDelete4 6 8 10
6 9 12 15
8 12 16 20
10 15 20 25
12 18 24 30
14 21 28 35
16 24 32 40
18 27 36 45
20 30 40 50
# column type table print
for i in 1..10
for j in 2..5
z = j*i
print z, "\t "
end
puts ()
end
puts
2 4 6 8 10 12 14 16 18 20
ReplyDelete3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
# table print row type
for i in 2..5
for j in 1..10
z = j*i
print z, " "
end
puts ()
end
puts
1
ReplyDelete2 2
3 3 3
4 4 4 4
5 5 5 5 5
# trianle shape
for x in 1..5
for y in 1..x
print x, " "
end
puts ()
end
puts
12345
ReplyDelete1234
123
12
1
# start prog
for x in 5.downto(1)
for y in 1..x
print y
end
puts ()
end
puts
54321
ReplyDelete5432
543
54
5
for x in 1..5
for y in 5.downto(x)
print y
end
puts ()
end
puts
1
ReplyDelete12
123
1234
12345
for x in 5.downto(1)
for y in 1..6-x
print y
end
puts
end
puts
11111
ReplyDelete2222
333
44
5
for x in 1..5
for y in 1..6-x
print x
end
puts ()
end
puts
5
ReplyDelete44
333
2222
11111
for x in 5.downto(1)
for y in 1..6-x
print x
end
puts ()
end
puts
ij
ReplyDelete11
22
33
44
55
puts "ij"
for i in 1..5
ch = 2
for j in 1..2
if i%2 == 0 && i%4 != 0
print ch
else
print i
end
end
puts
end
ij
ReplyDelete15
24
33
42
51
puts "ij"
for i in 1..5
for j in 1..2
end
print i
j = 6-i
print j
puts
end
*
ReplyDelete***
*****
***
*
# star pattern
ch = 2
for i in 1..5
if i <= 3
for k in 1..5-i
print " "
end
for j in 1..i*2-1
print "*"
end
else
for k in (5-i)..3
print " "
end
for j in 1..2*(ch)-1
print "*"
end
ch -= 1
end
puts
end
*
ReplyDelete* *
* * *
* * * *
* * * * *
for x in 1..5
for y in 1..x
print "*", " "
end
puts ""
end
*****
ReplyDelete****
***
**
*
for x in 1..5
ch = "*"
for y in 1..6-x
print ch
end
puts
end
A B C D E
ReplyDeleteA B C D
A B C
A B
A
for i in 1..5
ch = 65
for j in 1..6-i
print (ch.chr), " "
ch += 1
end
puts
end
puts
A
ReplyDeleteA B
A B C
A B C D
A B C D E
for x in 5.downto(1)
ch = 65
for y in 1..6-x
print (ch.chr), " "
ch += 1
end
puts
end
puts
@
ReplyDelete@ ?
@ ? >
@ ? > =
@ ? > = <
for x in 5.downto(1)
ch = 64
for y in 1..6-x
print (ch.chr), " "
ch -= 1
end
puts
end
puts
E D C B A
ReplyDeleteE D C B
E D C
E D
E
for x in 69.downto(65-1)
ch = 69
for y in 65..x
print (ch.chr), " "
ch -= 1
end
puts
end
A B C D E
ReplyDeletea b c d
A B C
a b
A
for x in 69.downto(65)
ch = 97
for y in 65..x
if x%2 == 0
print (ch.chr), " "
ch += 1
else
print (y.chr), " "
end
end
puts
end
A
ReplyDeletea b
A B C
a b c d
A B C D E
for x in 65..69
ch = 97
for y in 65..x
if x%2 == 0
print (ch.chr), " "
ch += 1
else
print (y.chr), " "
end
end
puts
end
A a B b C
ReplyDeleteA a B b
A a B
A a
A
for i in 1..5
ch = 65
for j in 1..6-i
if j%2 == 0
print (ch.to_i++32).chr, " "
ch += 1
else
print ch.chr, " "
end
end
puts
end
1 0 0 1 0
ReplyDelete1 0 0 1
1 0 0
1 0
1
for x in 1..5
ch = 1
ch1 = 0
for y in 1..6-x
if y%2 == 0
print (ch1), " "
ch1 = 1
else
print (ch), " "
ch = 0
end
end
puts
end
1 2 3 4 5
ReplyDelete5 4 3 2
1 2 3
5 4
1
for i in 1..5
for j in 1..6-i
if i%2 == 0
print (6-j), " "
else
print j, " "
end
end
puts
end
WAP to find fibonacci series.
ReplyDeletea = 0
b = 1
for i in 0..11
c = a+b
puts c
a=b
b=c
end
WAP TO FIND MAX SECOND MAX AND THIRD MAX NUMBER.
ReplyDeleteputs "enter mobile number"
mobile=gets().to_i
m=0
sm=0
tm=0
while mobile!=0
num=mobile%10
if m<num
tm=sm
sm=m
m=num
elsif sm<num
tm=sm
sm=num
elsif tm<num
tm=num
end
mobile=mobile/10
end
puts m, sm, tm
WAP TO FIND MAX AND SECOND MAX NUMBER OF ANY NUMBER.
ReplyDeleteputs "enter number"
num=gets().to_i
m=0
sm=0
while num!=0
a=num%10
num=num/10
if m<a
sm=m
m=a
elsif sm<a && num!=m
sm=a
end
end
puts "the max digit is #{m}, and the second digit number is #{sm}"
WAP TO SUM OF ODD NUMBER.
ReplyDeleteputs "enter number"
num=gets().to_i
if num%2!=0
for i in 1..11
k = num*i
puts k
end
else
puts "enter only odd number"
end
WAP TO SUM OF EVEN NUMBER.
ReplyDeleteputs "enter number"
num=gets().to_i
if num%2==0
for i in 0..10
k = num*i
puts k
end
else
puts "enter only even number"
end
# separate message enter username password invalid and try again only two times in do-while loop
ReplyDeletei = 1
loop do
print "Enter Username: "
uname = gets.chomp()
print "Enter Password: "
pass = gets.chomp()
if uname == "reshu"
if pass == "singh"
puts "Correct Username & Password "
break
else
puts "Invalid password"
print "try again [y/n]: "
num = gets.chomp
if num == "y"
else
break
end
end
else
puts "Invalid username"
print "try again [y/n]: "
num = gets.chomp
if num == "y"
else
break
end
i += 1
if i == 3
puts "Sorry, only two times use"
break
end
end
end
A B C D E
ReplyDeleteA B C D
A B C
A B
A
ANSWER:-
for i in 1..5
c=65
for j in 1..6-i
print (c.chr)
c=c+1
end
puts()
end
10010
ReplyDelete1001
100
10
1
ANSWER:-
for i in 1..5
a=1
b=0
for j in 1..6-i
if j%2==0
print b
b =1
else
print a
a=0
end
end
puts()
end
12345
ReplyDelete5432
123
54
1
ANSWER:-
for i in 1..6
for j in 1..6-i
if i%2==0
print 6-j
else
print j
end
end
puts()
end
1
ReplyDelete12
123
1234
12345
ANSWER:-
for i in 1..5
for j in 1..i
print j
end
puts()
end
A
ReplyDeleteAB
ABC
ABCD
ABCDE
ANSWER:-
for i in 1..5
c=65
for j in 1..i
print (c.chr)
c=c+1
end
puts()
end
WAP TO CALCULATE FACTORIAL .
ReplyDeleteputs "enter number to calculate factorial"
num=gets().to_i
i=num
f=1
while i>=1
f=f*i
i=i-1
end
puts "factorial is #{f}"
*
ReplyDelete**
***
****
*****
ANSWER:-
for i in 1..5
for j in 1..i
print "*"
end
puts()
end
*
ReplyDelete* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
ANSWER:-
for i in 0..10
print " "*(10-i), "* "*i, "\n"
end
*
ReplyDelete* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
answer:-
puts "enetr number"
rows=gets().to_i
for i in 0..rows
print "* "*i, "\n"
end
WAP TO REVERSE ANY NUMBER.
ReplyDeleteputs "enter number"
num=gets().to_i
s = ""
while num!=0
a=num%10
num=num/10
s = s + a.to_s
end
puts s
A a B b C
ReplyDeleteA a B b
A a B
A a
A
for i in 1..5
ch = 65
for j in 1..6-i
if j%2 == 0
print (ch.to_i++32).chr, " "
ch += 1
else
print ch.chr, " "
end
end
puts
end
map() method :- map() is a array class which return a new array containing the value returned by the block.
ReplyDeleteThe main use of map is transform data.
Q. multiply each element of an array by 2.
array = [12,34,56,77,88,99]
print array.map { |num| num*2 }, "\n"
[24, 68, 112, 154, 176, 198]
include method:-The include? method checks to see if the argument given is included in the array.
ReplyDeletea = [1,2,3,4,5,6]
print a.include?(5), "\n"
output:- true
concat():- concat() is a Array class method which returns the array after appending the two arrays together.
ReplyDeletea = [23,4,5,6,7,8]
b = [4.56,77,88,75]
c = [23,45,66,77,88]
puts " combining a and b : #{a.concat(b)}"
puts " combining b and c : #{b.concat(c)}"
puts "combining c and a : #{c.concat(a)}"
combining a and b : [23, 4, 5, 6, 7, 8, 4.56, 77, 88, 75]
combining b and c : [4.56, 77, 88, 75, 23, 45, 66, 77, 88]
combining c and a : [23, 45, 66, 77, 88, 23, 4, 5, 6, 7, 8, 4.56, 77, 88, 75]
# 2) WAP to find the max and second max and third max element in an array?
ReplyDeletearr = [1,9,6,7,4,3,2,5]
for i in 0...arr.length
for j in i+1...arr.length
if arr[i] < arr[j]
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
end
end
end
print "sorting Array: #{arr}"
puts
print "Find largest number: #{arr[0]}"
puts
print "Find second largest number: #{arr[1]}"
puts
print "Find third largest number: #{arr[2]}"
# 6) WAP to display prime elements in the array?
ReplyDeletearr = [45,67,2,45,78,9,8,47,13]
for i in 0...arr.length
c=0
for j in 2...arr[i]
if arr[i]%j == 0
c = 1
break
end
end
if c == 0 && arr[i]>1
puts arr[i]
end
end
# Element sort asending order
ReplyDeleteprint "Enter array size: "
size = gets.to_i
arr = []
for j in 0...size
print "Enter element: "
ele = gets.to_i
arr.append(ele)
end
for i in 0...size
for j in 0...(size-i-1)
if arr[j] > arr[j+1]
t = arr[j]
arr[j] = arr[j+1]
arr[j+1] = t
end
end
end
print "Element sort asending order: #{arr}"
# Element sort decending order
ReplyDeletearr = [12,89,6,11,6,4,78]
for i in 0...arr.length
for j in i+1...arr.length
if arr[i] < arr[j]
t = arr[i]
arr[i] = arr[j]
arr[j] = t
end
end
end
puts
print "Element sort decending order: #{arr}"
# Multiplication of two matrix
ReplyDeleteputs "Multiplication of two matrix"
a = [[1,4,6],[2,8,78]]
b = [[67,90,87],[3,45,21]]
c = [[0,0,0],[0,0,0]]
for i in 0...a.length
for j in 0...a[0].length
c[i][j] = a[i][j] * b[i][j]
end
end
for arr in c
print arr
puts
end
# Addition of two matrix
ReplyDeleteputs "Addition of two matrix"
a = [[1,4,6],[2,7,5]]
b = [[7,0,3],[3,2,1]]
c = [[0,0,0],[0,0,0]]
for i in 0...a.length
for j in 0...a[0].length
c[i][j] = a[i][j] + b[i][j]
end
end
print c
# 4) WAP to calculate compound interest using no return type function.
ReplyDeletedef compound_interest
print "Enter Principal amount: "
pr = gets.to_f
print "Enter Annual nominal interest rate as a decimal: "
rate = gets.to_f
print "Enter number of compounding periods per unit of time: "
n = gets.to_i
print "Enter time in decimal years: "
t1 = gets.to_i
# e.g., time in decimal years 6 months is calculated as 0.5 years
t = t1/2.to_f
# Annual nominal interest rate as a decimal calculate
r = rate/100
# formula based calculate compound_interest
cal = pr*(1+r/n)**(n*t)
puts "The total amount accrued," +
" principal plus interest," +
" with compound interest on a principal" +
" of $#{pr} at a rate of #{rate} per year compounded #{n} times per year" +
" over #{t} years is $#{cal}."
end
compound_interest() # calling method
# 3) WAP to create a salary calculator using no return type function
ReplyDeletedef salary
print "Enter basic: "
basic = gets.to_i
print "Enter Travel Allowance: "
ta = gets.to_i
print "Enter Dearness Allowance: "
da = gets.to_i
print "Enter Commission: "
comm = gets.to_i
print "Enter Provident Fund: "
pf = gets.to_i
print "Enter House Rent Allowance: "
hra = gets.to_i
print "Enter total leave: "
leave = gets.to_i
# calculation
lv = ta+da+comm
lv1 = basic/30
lvdeduction = lv1*(30-leave)
total = lvdeduction+lv-pf-hra
puts "Total salary in-hand #{total}"
end
salary()
# 3) Create a Sorting program using parametrized function?
ReplyDeletedef sort_method(*arr)
for i in 0...arr.length
for j in i+1...arr.length
if arr[i] > arr[j]
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
end
end
end
arr.each do |k|
print k, " "
end
end
sort_method(12,89,6,11,8,1,2)
WAP to create complete biodata for a marriage proposal?
ReplyDeletef = File.new("biodata.txt","w")
if f
puts("Enter your name")
name=gets
puts("Enter your father name ")
name1=gets
puts "enter mobile number"
num=gets
puts "enter your date of birth"
dob=gets
puts "enter occupation"
occupation=gets
puts "manglik"
mangkil=gets
puts "enter zodiac"
zodiac=gets
puts "what is your education"
education=gets
puts "address"
add=gets
f.syswrite("name is #{name}
and father name is #{name1}
and mobile number is #{num}
and dob is #{dob}
and occupation is #{occupation}
and mangkil #{mangkil}
and zodiac is #{zodiac}
and eduactiob is #{education}
and address is #{add}")
end
WAP to perform the addition of two numbers and write the output of addition under file?
ReplyDeletef = File.new("addition.txt", "w+")
puts "enter first number"
num1=gets().to_i
puts "enter second number"
num2=gets().to_i
num3=num1+num2
f.syswrite("addition is #{num3}")
WAP to create horoscope software?
ReplyDeletef = File.new("horoscope.txt", "w")
if f
puts "aries"
aries=gets
puts "Taurus"
taurus=gets
puts "Cancer"
cancer=gets
puts "Leo"
leo=gets
puts "Virgo"
virgo=gets
puts "Libra"
libra=gets
puts "scorpio"
scorpio=gets
puts "Sagittarius"
sagittarius=gets
puts "Capricon"
capricon=gets
puts "Aquarius"
aquarius=gets
puts "Pisces"
pisces=gets
f.syswrite("aries:- #{aries}
Taurus:- #{taurus}
Cancer:- #{cancer}
Leo:- #{leo}
Virgo:- #{virgo}
Libra:- #{libra}
scorpio:-#{scorpio}
Sagittarius:- #{sagittarius}
Capricon:- #{capricon}
Aquarius:- #{aquarius}
pisces:- #{pisces}")
end
# 3) WAP to create horoscope software?
ReplyDelete# write and read file
f = File.open("horoscope.txt", "r+")
a = "Arise:- The first sign of the zodiac, Aries loves to be number one. Naturally, this dynamic fire sign is no stranger to competition"
f.puts a
t = "Taurus:- Taurus is an earth sign represented by the bull."
f.puts t
g = "Gemini:- Appropriately symbolized by the celestial twins, this air sign was interested in so many pursuits that it had to double itself."
f.puts g
l = "Libra:- Libra is obsessed with symmetry and strives to create equilibrium in all areas of life"
f.puts l
# read file
f.seek(0)
data = f.read()
puts "Aries\tTaurus\nGemini\tLibra"
print "Enter your horoscope: "
hero = gets.chomp()
if hero == "Arise" || hero == "a"
puts a
elsif hero == "Taurus" || hero == "t"
puts t
elsif hero == "Gemini" || hero == "g"
puts g
elsif hero == "Libra" || hero == "l"
puts l
else
puts "sorry! No horoscope available"
end
f.close
# horoscope
ReplyDelete# write file
f = File.open("horoscope1.txt", "w")
puts "Aries\tTaurus\nGemini\tLibra"
print "enter your horoscope: "
hero = gets.chomp()
if hero == "Arise" || hero == "a"
f.write "The first sign of the zodiac, Aries loves to be number one. Naturally, this dynamic fire sign is no stranger to competition"
elsif hero == "Taurus" || hero == "t"
f.write "Taurus is an earth sign represented by the bull."
elsif hero == "Gemini" || hero == "g"
f.write "Appropriately symbolized by the celestial twins, this air sign was interested in so many pursuits that it had to double itself."
elsif hero == "Libra" || hero == "l"
f.write "Libra is obsessed with symmetry and strives to create equilibrium in all areas of life"
end
f.close
# read file
puts File.read("horoscope1.txt") # 1 way read file
puts IO.readlines("horoscope1.txt") # 2 way read file
# write and read file
ReplyDeletef = File.open("horoscope1.txt", "w+")
puts "Aries\tTaurus\nGemini\tLibra"
print "enter your horoscope: "
hero = gets.chomp()
if hero == "Arise" || hero == "a"
f.write "The first sign of the zodiac, Aries loves to be number one. Naturally, this dynamic fire sign is no stranger to competition"
elsif hero == "Taurus" || hero == "t"
f.write "Taurus is an earth sign represented by the bull."
elsif hero == "Gemini" || hero == "g"
f.write "Appropriately symbolized by the celestial twins, this air sign was interested in so many pursuits that it had to double itself."
elsif hero == "Libra" || hero == "l"
f.write "Libra is obsessed with symmetry and strives to create equilibrium in all areas of life"
end
f.seek(0)
data = f.read()
puts data
f.close
# 1) Count total vowel and consonant in String?
ReplyDeleteprint "Enter string: "
s = gets.chomp()
count = 0
cnt = 0
for i in 0...s.length
if s[i] == 'a' || s[i]=='e' || s[i] =='i' || s[i]=='o' || s[i]=='u'
count += 1
elsif s[i] != 'a' || s[i]=='e' || s[i] =='i' || s[i]=='o' || s[i]=='u'
cnt += 1
end
end
puts "Number of vowels: #{count}"
puts "Number of consonents: #{cnt}"
# 6) WAP to validate email?
ReplyDeleteprint "enter email id: "
str = gets.to_s
c = 0
ch = 0
for i in 0...str.length
if str[i] == "@" || str[i] == "."
c += 1
else
ch += 1
end
end
if c == 2 && str.length>1
puts "Valid"
else
puts "Not valid"
end
puts "Special charecter count #{c}."
puts "All charecter count but not incude special charecter #{ch}."
puts
# 2 condition use in valid email
ReplyDeleteprint "Enter email ID: "
s = gets.chomp()
count = 0
for i in 0...s.length
if s[i] == "@" || s[i] == "." || s[i] == "_"
count += 1
elsif s[i] == "@" || s[i] == "."
count += 1
end
end
if count == 3 || count == 2 && s.length>1
puts "Valid Email"
else
puts "Not Valid Email"
end
# Convert lower case to upper case
ReplyDeleteputs "Enter the string: "
str = gets.chomp()
puts "select option! a) convert to lower case b) convert to upper case"
con = gets.chomp()
if con == "a"
for i in 0...str.length
if str[i] != str.length
ch = str[i].to_s
if ch >= "A" && ch <= "Z"
str[i] = (ch.ord+32).chr
else
str[i] = ch
end
end
end
puts str
end
if con == "b"
for i in 0...str.length
if str[i] != str.length
k = str[i].to_s
if k >= "a" && k <= "z"
str[i] = (k.ord-32).chr
else
str[i] = k
end
end
end
puts str
end
s = "reshu"
ReplyDeletes1 = ""
for i in 0...s.length
s1 += (s[i].ord-32).chr
end
puts s1
# Program to convert String in Opposite case?
ReplyDeleteprint "Enter string upper/lower: "
s = gets.chomp()
s1 = ""
for i in (s.length-1).downto(0)
if s[i].ord >= 65 && s[i].ord <= 91
s1 += (s[i].ord+32).chr
else
s1 += (s[i].ord-32).chr
end
end
puts s1
# Program to convert String in Opposite case?
ReplyDeleteprint "Enter string: "
s = gets.chomp()
for i in (s.length-1).downto(0)
print s[i]
end
puts
puts "Enter the string: "
ReplyDeletestr = gets.chomp()
puts "select option! a) convert to lower case b) convert to upper case"
con = gets.chomp()
if con == "a"
for i in 0...str.length
if str[i] != str.length
ch = str[i].to_s
if ch >= "A" && ch <= "Z"
str[i] = (ch.ord+32).chr
else
str[i] = ch
end
end
end
puts str
else
for i in 0...str.length
if str[i] != str.length
k = str[i].to_s
if k >= "a" && k <= "z"
str[i] = (k.ord-32).chr
else
str[i] = k
end
end
end
puts str
end
# password program
ReplyDeleteprint "Enter password: "
pass = gets.chomp()
count = 0
for i in 0...pass.length
if pass[i] == "@" || pass[i] == "." || pass[i] == "_"
count += 1
elsif pass[i] == "@" || pass[i] == "."
count += 1
end
end
if count == 3 && pass.length>8
puts "Strong"
elsif count == 2 && pass.length>8
puts "Medium"
else
puts "Week"
end
# 2) WAP to reverse String?
ReplyDeletestr = "gnihtemos"
reverse = ""
str.length.times do |i|
reverse.insert(i, str[-1-i].chr)
end
puts reverse
# 2 ay reverse
ReplyDeletestr = "gnihtemos"
j = str.length-1
for i in 0..str.length/2
k = str[i]
str[i] = str[j]
str[j] = k
j -= 1
end
puts str
# check palindromic
ReplyDeleteprint "Enter string: "
str = gets.chomp()
s = (str.length)/2
rev = -1
for i in 0...s
if str[i] == str[rev]
rev -= 1
puts "polindrome"
break
else
puts "not polindrome"
break
end
end
# 4) Count total numeric char in String?
ReplyDeletes ="reshu 543678 singh 3456"
count = 0
for i in 0...s.length
# if s[i] == '0'|| s[i] == '1' || s[i] == '2' || s[i] == '3' || s[i] == '4' || s[i] == '5' || s[i] == '6' || s[i] == '7' || s[i] == '8' || s[i] == '9'
if s[i] >= "0" && s[i] <= "9"
print s[i]
count += 1
end
end
puts
puts count
# table print using recursion
ReplyDeleteputs "Table print"
$a = 1
def sum(num)
if $a > 10
return $a
else
b = $a * num
puts "#{num.to_s}" "*" "#{($a).to_s}" "=" "#{b}"
$a += 1
return sum(2)
end
end
sum(2)
puts "Fibonancci program"
ReplyDelete$a = 0
$b = 1
def func(num)
if num > 5
return num
else
sum = $a + $b
print sum, " "
$a = $b
$b = sum
return func(num+1)
end
end
func(1)
puts
# fibonancci series in recursion
ReplyDeleteputs "Fibonancci program without using global variable"
def func(a, b, num)
if num < 0
return num
else
sum = a + b
print sum, " "
a = b
b = sum
return func(a, b, num-1)
end
end
a = 0
b = 1
func(a, b, 5)
puts
# addition using recursion
ReplyDeleteputs "Sum of number"
$a = 0
def sum(num)
if num > 5
return $a
else
$a += num
puts "#{num.to_s}" "+" "#{($a-num).to_s}" "=" "#{$a}"
return sum(num + 1)
end
end
sum(1)
# # calculate factorial using recursion
ReplyDeleteputs "Calculate factorial"
$a = 1
def fact(num)
if num == 1
return $a
else
$a *= num
return fact(num - 1)
end
end
fact(5)
puts "Factorial of 5 is #{$a}."
# 6) WAP to find total prepositions in a paragraph
ReplyDelete# using predefine method
s = "Your book is on the table. She was behind you"
arr = s.split(" ")
c = 0
for i in 0...s.length
if arr[i] == "on" || arr[i] == "behind"
c += 1
end
end
if c == 2 && arr.length>2
puts "Total preposition #{c}"
else
puts "not"
end
# not using predefine method
ReplyDeletes = "Your", "book", "is", "on", 'the', 'table.', 'She', 'was', 'behind', "you"
c = 0
for i in 0...s.length
if s[i] == "on" || s[i] == "behind"
c += 1
end
end
if c == 2 && s.length>2
puts "Total preposition #{c}"
else
puts "not"
end
# fibonancci series in recursion
ReplyDeleteputs "Fibonancci program"
$a = 0-1
$b = 1-0
def func(num)
if num > 5
return num
else
sum = $a + $b
print sum, " "
$a = $b
$b = sum
return func(num+1)
end
end
func(1)
# simple way sum of even and odd number using recursion
ReplyDelete$b = 5
$c = 0
$d = 0
def func(a)
if a <= $b
if a%2 == 0
$c += a
else
$d += a
end
else
puts $c
puts $d
return 0
end
return func(a+1)
end
a = 1
func(a)
# sum of even and odd number using recursion
ReplyDelete$count1 = 1
$count2 = 1
def func(a,b,c,d)
if a <= b
if a%2 == 0
puts "Even number #{$count1}: #{a}"
puts "add #{c}" + "+" + "#{a}" + "=" + "#{c+a}"
c += a
$count1 += 1
else
puts "Odd number #{$count2}: #{a}"
puts "add #{d}" + "+" + "#{a}" + "=" + "#{d+a}"
d += a
$count2 += 1
end
else
puts "Sum of total even number: #{c}"
puts "Sum of total odd number: #{d}"
return 0
end
return func(a+1,b,c,d)
end
a = 1
b = 6
c = 0
d = 0
func(a,b,c,d)
# sum of even and odd number using recursion
ReplyDeleteclass EvenOdd
$count1 = 0
$count2 = 0
def func(a,b,c,d)
if a <= b
if a%2 == 0
puts "Even number #{$count1+1}: #{a}"
puts "add #{c}" + "+" + "#{a}" + "=" + "#{c+a}"
c += a
$count1 += 1
else
puts "Odd number #{$count2+1}: #{a}"
puts "add #{d}" + "+" + "#{a}" + "=" + "#{d+a}"
d += a
$count2 += 1
end
else
puts "Total even #{$count1} sum even number: #{c}"
puts "Total odd #{$count2} sum odd number: #{d}"
return 0
end
return func(a+1,b,c,d)
end
end
print "Enter start number: "
a = gets.to_i
print "Enter ending number: "
b = gets.to_i
c = 0
d = 0
object = EvenOdd.new
object.func(a,b,c,d)
# simple interest calculate using class method
ReplyDeleteclass SI
def user_input()
print "Enter principal: "
@p = gets.to_i
print "Enter rate: "
@r = gets.to_i
print "Enter time: "
@t = gets.to_i
end
def variable_declare(p,r,t)
@p = p
@r = r
@t = t
end
def logic()
@SI = (@p*@r*@t)/100
end
def output()
puts "Calculate SI: #@SI"
end
end
obj = SI.new
obj.variable_declare(@p,@r,@t)
obj.user_input()
obj.logic()
obj.output()
# self onject use
ReplyDeleteclass SI
def self.variable_declare(p,r,t)
@p = p
@r = r
@t = t
end
def self.logic()
@SI = (@p*@r*@t)/100
end
def self.output()
puts "Calculate SI: #@SI"
end
end
print "Enter principal: "
p = gets.to_i
print "Enter rate: "
r = gets.to_i
print "Enter time: "
t = gets.to_i
SI.variable_declare(p,r,t)
SI.logic()
SI.output()
# squre cube calculate using class and object
ReplyDeleteclass Squre_cube
def define_var(s)
@s = s
end
def cal_sq()
@a = @s*@s
@b = @s*@s*@s
end
def output()
puts "#@s calculate squre: #@a"
puts "#@s calculate cube: #@b"
end
end
obj = Squre_cube.new
obj.define_var(2)
obj.cal_sq()
obj.output()
# range based squre cube calculate using class and object
ReplyDeleteclass Squre_cube
def define_var(start)
@s = start
end
def cal_sq()
@a = @s*@s
@b = @s*@s*@s
end
def output()
print "Calculate squre: #@a"
print "\t Calculate cube: #@b"
puts
end
end
print "Enter any number: "
start = gets.to_i
print "Enter last number: "
ending = gets.to_i
obj = Squre_cube.new
while start <= ending
obj.define_var(start)
obj.cal_sq()
obj.output()
start += 1
end
# even and odd number using class method
ReplyDeleteclass EvenOdd
def self.variable_declare(num)
@a = num
end
def self.logic()
@count = @a
end
def self.even_num()
puts "Even number: #@count"
end
def self.odd_num()
puts "odd number: #@count"
end
def self.sum_even()
puts "sum of total even number: #@a"
end
def self.sum_odd()
puts "sum of total odd number: #@a"
end
end
print "Enter start number: "
snum = gets.to_i
print "Enter ending number: "
lnum = gets.to_i
for i in snum..lnum
EvenOdd.variable_declare(i)
EvenOdd.logic()
if i%2 == 0
EvenOdd.even_num
else
EvenOdd.odd_num
end
i += 1
end
# sum of even and odd number and count even or odd
ReplyDeleteclass EvenOdd
def self.even_num(snum)
@a = snum
puts "Even number: #@a"
end
def self.odd_num(snum)
@b = snum
puts "odd number: #@b"
end
def self.sum_even(count1,c)
puts "Total count #{count1} even number and sum of even no: #{c}"
end
def self.sum_odd(count2,d)
puts "Total count #{count2} odd number and sum of odd no: #{d}"
end
end
print "Enter start number: "
snum = gets.to_i
print "Enter ending number: "
lnum = gets.to_i
count1 = 0
count2 = 0
c = 0
d = 0
for i in snum..lnum
if i%2 == 0
EvenOdd.even_num(i)
count1 += 1
c += i
else
EvenOdd.odd_num(i)
count2 += 1
d += i
end
i += 1
end
EvenOdd.sum_even(count1,c)
EvenOdd.sum_odd(count2,d)
# 2 way sum of even and odd number and count even or odd
ReplyDeleteclass EvenOdd
def self.variable_declare(snum)
@a = snum
end
def self.even_num()
puts "Even number: #@a"
end
def self.odd_num()
puts "odd number: #@a"
end
def self.sum_even(count1,c)
puts "Total count #{count1} even number and sum of even no: #{c}"
end
def self.sum_odd(count2,d)
puts "Total count #{count2} odd number and sum of odd no: #{d}"
end
end
print "Enter start number: "
snum = gets.to_i
print "Enter ending number: "
lnum = gets.to_i
count1 = 0
count2 = 0
c = 0
d = 0
for i in snum..lnum
EvenOdd.variable_declare(i)
if i%2 == 0
EvenOdd.even_num()
count1 += 1
c += i
else
EvenOdd.odd_num()
count2 += 1
d += i
end
i += 1
end
EvenOdd.sum_even(count1,c)
EvenOdd.sum_odd(count2,d)
* *
ReplyDelete** **
*** ***
**** ****
**********
for i in 1..5
for j in 1..i
print "*"
end
for k in 1..5*2-i*2
print " "
end
for l in 1..i
print "*"
end
puts()
end
* * *
ReplyDelete** ** **
*** *** ***
**** **** ****
***************
for i in 1..5
for j in 1..i
print "*"
end
for k in 1..5*2-i*2
print " "
end
for l in 1..i
print "*"
end
for m in 1..5*2-i*2
print " "
end
for n in 1..i
print "*"
end
puts()
end