Sei sulla pagina 1di 30

Ruby

Contents

 1 Introduction
 2 Data types
 3 Arrays
 4 exercise:1
 5 exercise:2
 6 exercise:3
 7 exercise:4
 8 exercise:5
 9 exercise:6
 10 exercise:7
 11 exercise:8
 12 exercise:9
 13 exercise:10
 14 exercise:11
 15 exercise:12
 16 exercise:14
 17 exercise:15
 18 exercise:16
 19 exercise:17
 20 exercise:18
 21 exercise:20
 22 exercise:21
 23 while loop
 24 exercise:22
 25 while modifier
 26 exercise:23
 27 until
 28 exercise:24
 29 until as modifier
 30 exercise:25
 31 for loop
 32 exercise:26
 33 loop using each method
 34 exercise:27
 35 using break
 36 exercise:1
 37 using next
 38 exercise:1
 39 using redo
 40 exercise:1
 41 using retry
 42 exercise:1
 43 Examples
 44 Exercise:1
 45 Exercise:2
 46 Exercise:3
 47 Example: 4
 48 Example: 5

Introduction

 puts “hello world!!”


 #This is a comment

puts “Hello world”


puts “welcome to Ruby” # Only after hash is comment

# comment 1
# comment 2
# comment 3
=begin
Here is another way of adding multiple comments
This is also comment
This is also comment
=end

puts “first line”


puts “second line”
puts “main program”
BEGIN{
puts “this will be printed in the beginning of the program”
}
END{
puts “this will be printed at the end of the program”
}

 Output:

 this will be printed in the beginning of the program


 main program
 this will be printed at the end of the program

Data types

 Assign the variable x to the value 5.

x = 5

 x is called a variable and 5 is the value. x is called a variable because it can be reassigned with
another value.

 What is the datatype of "Matt"?

"Matt" is a String. Strings are text that are surrounded by double or single
quotes ("Matt" and 'Matt' are acceptable syntax).
x = 5
Is x a string?
x is a variable and is not a string. 5 is assigned to the variable and 5 is
an Integer, not a String. Notice that variables are not surrounded
with quotation marks.

 vi datatypes1.rb

a = 4
puts a
puts “#{a}”

puts “I have a apples”


puts “I have #{a} apples”

name = “satheesh”

puts “my name is #{name}”

 # Variables not strongly typed

 vi datatypes2.rb

a = 4
puts "a is #{a}"

a = "apple"
puts "a is #{a}"

 Find type of class

 vi findclass.rb

puts 4.class
puts 3.14.class
puts “name”.class

Output:

 FixNum
 Float
 String

a = 4
puts a.class

a = “name”
puts a.class

 vi add.rb

a = 4
b = 5

puts a + b

 String concatenation

a = "Bat"
b = "woman"

 What does this expression evaluate to?

a + b
"Batwoman"

 vi stringConcatenate.rb

a = “bat”
b = “woman”
puts a + b

 What does this expression evaluate to?

"bob" + 42
 This raises an error because a number (Integer to be precise) cannot be concatenated with a
String.

 vi addStringAndNumer.rb

a = “bob”
b = 42
puts a + b

 Expression substitution is a means of embedding the value of any Ruby expression into a string
using #{ and }:

#!/usr/bin/ruby

x, y, z = 12, 36, 72
puts "The value of x is #{ x }."
puts "The sum of x and y is #{ x + y }."
puts "The average was #{ (x + y + z)/3 }."

 This will produce the following result:

The value of x is 12.


The sum of x and y is 48.
The average was 40.

 With general delimited strings, you can create strings inside a pair of matching though arbitrary
delimiter characters, e.g., !, (, {, <, etc.,
preceded by a percent character (%). Q, q, and x have special meanings. General delimited strings
can be

%{Ruby is fun.} equivalent to "Ruby is fun."


%Q{ Ruby is fun. } equivalent to " Ruby is fun. "
%q[Ruby is fun.] equivalent to a single-quoted string
%x!ls! equivalent to back tick command output `ls`
#!/usr/bin/ruby

myStr = String.new("THIS IS TEST") #One way of creating a new string


object
#myStr = "THIS" #This is another way
foo = myStr.downcase

puts "#{foo}"

Output:

this is test

 Here we have the venerable times method. Use it whenever you want to do something more
than once. Examples:

puts "I will now count to 99..."


100.times {|number| puts number}
5.times {puts "Guess what?"}
puts "I'm done!"

 This will print out the numbers 0 through 99, print out Guess what? five times, then say I'm done!
It's basically a simplified for loop. It's a little slower than a for loop by a few hundredths of a
second or so; keep that in mind if you're ever writing Ruby code for NASA. ;-)
 Alright, we're nearly done, six more methods to go. Here are three of them:

# First a visit from The Count...


1.upto(10) {|number| puts "#{number} Ruby loops, ah-ah-ah!"}

# Then a quick stop at NASA...


puts "T-minus..."
10.downto(1) {|x| puts x}
puts "Blast-off!"

# Finally we'll settle down with an obscure Schoolhouse Rock video...


5.step(50, 5) {|x| puts x}

 Alright, that should make sense. In case it didn't, upto counts up from the number it's called from
to the number passed in its parameter. downto does the same, except it counts down instead of
up.
 Finally, step counts from the number its called from to the first number in its parameters by the
second number in its parameters. So 5.step(25, 5) {|x| puts x} would output every multiple of five
starting with five and ending at twenty-five.

 Time for the last three:

string1 = 451.to_s
string2 = 98.6.to_s
int = 4.5.to_i
float = 5.to_f

 to_s converts floats and integers to strings. to_i converts floats to integers. to_f converts integers
to floats. There you have it. All the data types of Ruby in a nutshell. Now here's that quick
reference table for string methods.

Arrays

rapper = "Jaydacents"

 Get the first letter from the string "Jaydacents".

"Jaydacents"[0]
# OR
rapper[0]

 Basically everything in computer science is 0-indexed, so the counting starts at zero, not at 1.
 Get the first through 3rd elements from the "Jaydacents" string.

"Jaydacents"[0..2]

 Get the last element from the "Jaydacents" string.

"Jaydacents"[-1]

 Replace the "l" in the following string with "m":


word = "lace"
word[0] = "m"
puts word
=> "mace"

exercise:1

 vi stringArray.rb

#!/usr/bin/ruby

name=”satheesh”
puts name[0] #prints the first character in the name
puts name[-1] #prints the last character in the name
puts name[0,2] #prints 2 characters from first character

output:

s
h
sa

exercise:2

#!/usr/bin/ruby
a = [0,1,2,3,4]
puts a[0]
puts a [-1]
puts a[2] + 5
puts a[3] * 5

puts a[4] / 4

output:

0
4
7
15
1

exercise:3

#!/usr/bin/ruby

names = [“kiran”, “murali”, “rakesh”, “john”, “abdul” ]

puts names # prints all names

puts “replacing kiran with satheesh…..”

names[0] = “satheesh” #Replace kiran with satheesh in the array

puts “here are the items after updating”

puts names # prints updated elements from array

output :

kiran
murali
rakesh
john
abdul
replacing kiran with satheesh....
here are the items after updating
satheesh
murali
rakesh
john
abdul
exercise:4

h = {"hash?" => "yep, it\'s a hash!", "the answer to everything" =>


42, :linux => "fun for coders."}
puts "Stringy string McString!".class
puts 1.class
puts nil.class
puts h.class
puts :symbol.class

 displays

String
Fixnum
NilClass
Hash
Symbol

exercise:5

 What does this expression evaluate to?

"Cool".+("io")
"Coolio"

 This is another way to concatenate Strings. The previous example actually uses syntactic sugar
(a deviation from formal syntax to enhance code readability) and this example uses the strict
syntax.

exercise:6

 What does this expression print?

my_name = "50 Cent"


my_name = "Miley"
p my_name
"Miley"

 The my_name variable was assigned to the value "50 Cent", but then it was reassigned to the
value "Miley". Once the my_name variable is reassigned to "Miley", it loses all knowledge that it
used to point to "50 Cent".

 Assign the variable my_dawg to the value "DMX"

my_dawg = "DMX"

 What does the following expression evaluate to?

"Dead Poet" = fav_bar

 This raises an error. When variables are assigned, the variable must be on the left, follow by an
equal sign, followed by the value.

 What does the following expression print?

something = "cats"
crazy = something
puts crazy

 This will print "cats" because the variables something and crazy both point to the same value.

exercise:7

 What does the following expression evaluate to?

3 + 4
7
 What does the following expression evaluate to?

4 * 7
28

 What does the following expression evaluate to?

2 ** 3
8

 ** is used for exponents and 2 ** 3 is 2 to the power 3 or 2 * 2 * 2.

 What does the following expression evaluate to?

8 / 2
4

 What does the following expression evaluate to?

3 / 2
1

 This outcome is not 1.5 because we are performing Integer division (division between two
Integers) and Integers do not have any decimals. Division between two integers always results
in an integer.

 What does the following expression evaluate to?

3.0 / 2.0
1.5
 This outcome is 1.5 because we are performing division on Floating point numbers that have
decimals.
 3.0 / 2 and 3 / 2.0 also return 1.5.

exercise:8

 What does the following expression evaluate to?

"i am not shouting".upcase()


"I AM NOT SHOUTING"

 This shows that Ruby has nifty methods that are built in to the String class. The syntax for using
the built in methods is the value, followed by dot, followed by the method name.

 Convert every letter of "YoLo BrAh" to lowercase.

nice = "YoLo BrAh"


nice.downcase()
# OR
"YoLo BrAh".downcase()

 Concatenate the following strings:

first = "Beautiful "


second = "face tattoo"
first + second
# OR
first.+(second)
# OR
first.concat(second)

 The +() and concat() methods do the same thing (they're not exactly the same, but very similar).
Notice the similarity with the previous examples: there is a string, followed by a dot, followed by
the method names with another string as an argument.
 Integers have useful built-in methods too. Convert the number 5 to the string "5".

5.to_s
to_s stands for "to string"

 What is the problem with the following code?

my variable = "Mr. White"

 This will raise an error because variables cannot have spaces in them. Ruby convention is to
combine multi-word variable names with an underscore.

my_variable = "Mr. White"

 Update the code, so it can run successfully:

exercise:9

band = "Blink" + 182

 We cannot concatenate a String and an Integer. However, we can convert the Integer to a String
first and then concatenate the values as two Strings.

band = "Blink" + 182.to_s


puts "I will now count to 99..."
100.times {|number| puts number}
5.times {puts "Guess what?"}
puts "I'm done!"
# First a visit from The Count...
1.upto(10) {|number| puts "#{number} Ruby loops, ah-ah-ah!"}
# Then a quick stop at NASA...
puts "T-minus..."
10.downto(1) {|x| puts x}
puts "Blast-off!"

# step down...
5.step(50, 5) {|x| puts x}

# Outputs 1585761545
"Mary J".hash
# Outputs "concatenate"
"concat" + "enate"
# Outputs "Washington"
"washington".capitalize
# Outputs "apple"
"APPLE".downcase
# Outputs "ORANGE"
"orange".upcase
# Outputs "Henry VII"
"Henry VIII".chop
# Outputs "rorriM"
"Mirror".reverse
# Outputs 810
"All Fears".sum
# Outputs cRaZyWaTeRs
"CrAzYwAtErS".swapcase
# Outputs "Nexu" (next advances the word up one value, as if it were a
number.)
"Next".next
# After this, nxt == "Neyn" (to help you understand the trippiness of next)
nxt = "Next"
20.times {nxt = nxt.next}
myStr = String.new("THIS IS TEST")
foo = myStr.downcase

puts "#{foo}"
 This will produce the following result:

this is test

exercise:10

#!/usr/bin/ruby

ary = [1,2,3,4,5]
ary.each do |i|
puts i
end

 This will produce the following result:

1
2
3
4
5

exercise:11

a = [ 1,2,3,4,5]

#prints 4th element of array


puts a[3]

#prints length of the array


puts a.length

#happend element to array

a << 6

puts a[5]
puts a.length

#prints elements multiplied by 2


a.each do |i|
puts i*2

end

exercise:12

#!/usr/bin/ruby

a = [1,2,3,4,5]
b = Array.new
b = a.collect
puts b

 This will produce the following result:

1
2
3
4
5

exercise:13

 #!/usr/bin/ruby

a = [1,2,3,4,5]
b = a.collect{|x| 10*x}
puts b

 This will produce the following result:

10
20
30
40
50

exercise:14

hash = { :leia => "Princess from Alderaan", :han => "Rebel without a
cause", :luke => "Farmboy turned Jedi"}

#Print each value of keys


puts hash[:leia]
puts hash[:han]
puts hash[:luke]

#Print all the values


hash.each do |key, value|
puts value
end

 If I want to remove luke, I could do something like this:

hash.delete(:luke)

 Now Luke's no longer in the hash. I could do this:

hash.delete_if {|key, value| value.downcase.match("farmboy")}

 I could add matt into the mix by assigning a new value to the hash:

hash[:matt] = "Dashing administrator."

 Expression substitution is a means of embedding the value of any Ruby expression into a string
using #{ and }:
exercise:15

#!/usr/bin/ruby

x, y, z = 12, 36, 72
puts "The value of x is #{ x }."
puts "The sum of x and y is #{ x + y }."
puts "The average was #{ (x + y + z)/3 }."

 This will produce the following result:

The value of x is 12.


The sum of x and y is 48.
The average was 40.

exercise:16

#!/usr/bin/ruby

x=1
if x > 2
puts "x is greater than 2"
elsif x <= 2 and x!=0
puts "x is 1"
else
puts "I can't guess the number"
end

output:

x is 1

exercise:17

#!/usr/bin/ruby
$var = 1
print "1 -- Value is set\n" if $var
print "2 -- Value is set\n" unless $var

$var = false
print "3 -- Value is set\n" unless $var

 This will produce the following result:

1 -- Value is set
3 -- Value is se

exercise:18

#!/usr/bin/ruby

$age = 5
case $age
when 0 .. 2
puts "baby"
when 3 .. 6
puts "little child"
when 7 .. 12
puts "child"
when 13 .. 18
puts "youth"
else
puts "adult"
end

 This will produce the following result:

little child

exercise:19
#!/usr/bin/ruby

def test(a1="Ruby", a2="Perl")

puts "The programming language is #{a1}"


puts "The programming language is #{a2}"
end
test "C", "C++"
test

 This will produce the following result:

The programming language is C


The programming language is C++
The programming language is Ruby
The programming language is Perl

exercise:20

#!/usr/bin/ruby

def test
i = 100
j = 200
k = 300
return i, j, k
end
var = test
puts var

 This will produce the following result:

100
200
300

exercise:21

#!/usr/bin/ruby

def sample (*test)


puts "The number of parameters is #{test.length}"
for i in 0...test.length
puts "The parameters are #{test[i]}"
end
end
sample "Zara", "6", "F"
sample "Mac", "36", "M", "MCA"

 In this code, you have declared a method sample that accepts one parameter test. However,
this parameter is a variable parameter. This means that this parameter can take in any number
of variables. So above code will produce following result:

The number of parameters is 3


The parameters are Zara
The parameters are 6
The parameters are F
The number of parameters is 4
The parameters are Mac
The parameters are 36
The parameters are M
The parameters are MCA

while loop
exercise:22

#!/usr/bin/ruby

$i = 0
$num = 5

while $i < $num do


puts("Inside the loop i = #$i" )
$i +=1
end

 This will produce the following result:

Inside the loop i = 0


Inside the loop i = 1
Inside the loop i = 2
Inside the loop i = 3
Inside the loop i = 4

while modifier
exercise:23

#!/usr/bin/ruby

$i = 0
$num = 5
begin
puts("Inside the loop i = #$i" )
$i +=1
end while $i < $num

 This will produce the following result:

Inside the loop i = 0


Inside the loop i = 1
Inside the loop i = 2
Inside the loop i = 3
Inside the loop i = 4
until
exercise:24

#!/usr/bin/ruby

$i = 0
$num = 5

until $i > $num do


puts("Inside the loop i = #$i" )
$i +=1;
end

 This will produce the following result:

Inside the loop i = 0


Inside the loop i = 1
Inside the loop i = 2
Inside the loop i = 3
Inside the loop i = 4
Inside the loop i = 5

until as modifier
exercise:25

#!/usr/bin/ruby

$i = 0
$num = 5
begin
puts("Inside the loop i = #$i" )
$i +=1;
end until $i > $num
 This will produce the following result:

Inside the loop i = 0


Inside the loop i = 1
Inside the loop i = 2
Inside the loop i = 3
Inside the loop i = 4
Inside the loop i = 5

for loop
exercise:26

#!/usr/bin/ruby

for i in 0..5
puts "Value of local variable is #{i}"
end

 Here, we have defined the range 0..5. The statement for i in 0..5 will allow i to take values in the
range from 0 to 5 (including 5). This will produce the following result:
Value of local variable is 0 Value of local variable is 1 Value of local variable is 2 Value of local
variable is 3 Value of local variable is 4 Value of local variable is 5

loop using each method


exercise:27

#!/usr/bin/ruby

(0..5).each do |i|
puts "Value of local variable is #{i}"
end

 This will produce the following result:


Value of local variable is 0
Value of local variable is 1
Value of local variable is 2
Value of local variable is 3
Value of local variable is 4
Value of local variable is 5

using break
exercise:1

1. !/usr/bin/ruby

for i in 0..5
if i > 2 then
break
end
puts "Value of local variable is #{i}"
end

 This will produce the following result:

Value of local variable is 0


Value of local variable is 1
Value of local variable is 2

using next
exercise:1

#!/usr/bin/ruby

for i in 0..5
if i < 2 then
next
end
puts "Value of local variable is #{i}"
end

 This will produce the following result:

Value of local variable is 2


Value of local variable is 3
Value of local variable is 4
Value of local variable is 5

using redo
exercise:1

#!/usr/bin/ruby

for i in 0..5
if i < 2 then
puts "Value of local variable is #{i}"
redo
end
end

 This will produce the following result and will go in an infinite loop:
Value of local variable is 0 Value of local variable is 0

using retry
exercise:1

#!/usr/bin/ruby

for i in 1..5
retry if i > 2
puts "Value of local variable is #{i}"
end

This will produce the following result and will go in an infinite loop:
Value of local variable is 1
Value of local variable is 2
Value of local variable is 1
Value of local variable is 2
Value of local variable is 1
Value of local variable is 2

Examples
Exercise:1

 Create a program to capture the user’s name and print welcome message to the user

print "Please enter your name : "


name = STDIN.gets

puts “welcome #{name} to ruby world”

Exercise:2

 Create a program to capture the user’s name and print the name in reverse

print "Please enter your name : "


name = STDIN.gets

puts “welcome #{name.reverse} to ruby world”

Exercise:3

 Create a program to capture an integer and print whether it is odd number or even number.

#!/usr/bin/ruby

print "Please enter an integer : "


x = STDIN.gets

if x.to_i % 2 == 0
puts "it is even number"
else
puts "it is odd number"
end

Example: 4

 Create a program to read input parameters and print the count of the parameters

#!/usr/bin/ruby
puts "you have passed " + ARGV.length.to_s + " parameters"

Example: 5

 Create a program to get the user inputs for name, age, experience for 4 users and put them in
csv file.

#!/usr/bin/ruby

2.times do |i|
h = {}
print "Please enter name : "
h['name'] = STDIN.gets.chomp
print "Please enter age : "
h['age'] = STDIN.gets.chomp
print "Please enter experience in years : "
h['exp'] = STDIN.gets
#print h.values.join(',')
File.write('list.csv', h.values.join(','))
end

Potrebbero piacerti anche