Ruby From Beginning

Aus xinux.net
Zur Navigation springen Zur Suche springen

Hello World

#!/usr/bin/ruby
puts "Hello World!"

What is your name?

#!/usr/bin/ruby
print "What is your name? "
name = gets
puts  "Your name is #{name}"

Heredocument

#!/usr/bin/ruby
print <<EOF
   This is the first way of creating
  here document ie. multiple line string.
EOF

ARGS from the Console

#!/usr/bin/ruby
puts ARGV[0] 
puts ARGV[1] 
puts ARGV[2]

Read a file

#!/usr/bin/ruby
puts "What file do you want to read? "
Filename = gets
Filename.delete!("\n")
TheFile = File.read( Filename )
puts TheFile.to_s

Write in a file

#!/usr/bin/ruby
puts "write"
VarFile = File.new("dat.txt", "w+")           
VarFile.puts "das erste "                    
VarFile.puts "das zweite"                     
VarFile.close

IF Statement

#!/usr/bin/ruby
 puts "Number?: "
 x = gets
 if x.to_i > 2
    puts "x is greater than 2"
 elsif x.to_i <= 2 and x.to_i != 0
    puts "x is 1"
 else
    puts "I can't guess the number"
 end

CASE Statement

#!/usr/bin/ruby
print "Enter your grade: "
grade = gets.chomp
case grade
when "A"
  puts 'You pretty smart!'
when "B"
  puts 'You smart!'
 when "C", "D"
  puts 'You pretty dumb!!'
else
  puts "You can't even use a computer!"
end

WHILE Statement

#!/usr/bin/ruby
$i = 0
$num = 5 
while $i < $num  do
   puts("Inside the loop i = #$i" )
   $i +=1
end

FOR Statement

#!/usr/bin/ruby
for i in 0..5
   puts "Value of local variable is #{i}"
end

OR

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

Methods

#!/usr/bin/ruby
def test(a1 = "Ruby", a2 = "Perl")
   puts "The programming language is #{a1}"
   puts "The programming language is #{a2}"
end

Class

#!/usr/bin/ruby
class Sample
   def hello
      puts "Hello Ruby!"
   end
end

Instance of a class

object = Sample.new
object.hello

Everything is a class

1.upto(3) { |i| puts i }    # 1 2 3
3.downto(1) { |i| puts i }  # 3 2 1
0.step(10,2) { |i| puts i } # 0 2 4 6 8 10
3.times { puts "42" }       # 42 42 42

Links