Увођење Руби команди
1. Шта је Руби?
Руби је програмски језик отвореног кода. Интерпретира се као и објектно оријентисана. Руби је креирао Иукихиро Матсумото. Руби је добила име по драгуљу и стога га је аутор створио као драгуљ програмских језика. овде ћемо разговарати о различитим типовима Руби команди.
Дизајн Руби-а узима у обзир следеће факторе - Једноставност, Екстензивност, Потпуност и преносивост. Руби ради на већини УНИКС платформи. Велики део Руби-а изграђен је на Линуку. Руби такође ради на уобичајеним платформама као што су Виндовс, ДОС, Мац, итд.
Као и Руби команде
1. Једноставна наредба за штампање низа у Руби-у
#!/usr/bin/ruby –w
puts “Hello, Ruby!”
2. Једноставна наредба за штампање низа низова помоћу ЕОФ
#!/usr/bin/ruby –w
print < Multiple line string.
First wayEOF
print <<"EOF"; # same as above
Multiple line string.
Second way
EOF#!/usr/bin/ruby –w
print < Multiple line string.
First wayEOF
print <<"EOF"; # same as above
Multiple line string.
Second way
EOF
3. Једноставна наредба за штампање низа низова помоћу извршавања наредбе
#!/usr/bin/ruby –w
print <<`EOC` # execute commands
echo First Statement
echo Second Statement
EOC
4. Једноставна команда за штампање низа више редака слагањем.
#!/usr/bin/ruby –w
print <<"a", <<"b" # you can stack them
I said foo.
a
I said bar.
b
5. Руби БЕГИН изјава
#!/usr/bin/ruby
puts "This statement comes later"
BEGIN (
puts "This statement will be printed in the beginning"
)
6. Руби ЕНД изјава
#!/usr/bin/ruby
puts "This is main body"
END (
puts "This block executes in the end"
)
BEGIN (
puts "This block executes in the beginning"
)
7. Руби једноредни коментар
#!/usr/bin/ruby
# This is a single line comment.
uts "This is not a comment" # This is again a single line
comment.
8. Руби вишеструки коментар
#!/usr/bin/ruby=begin
This is a multiple line comment.=end
puts "This is not a comment" # This is a single line comment.
9. Функција члана у класи Руби. Креирање објекта и позивање методе.
#!/usr/bin/ruby
class Demo
def testmethod
puts "Hello World!"
end
end
# Now using above class to create objects
object = Demo.new
object.testmethod
10. Глобалне променљиве у Руби-у
#!/usr/bin/ruby
$globalvariable=123
class FirstClass
def printglobal
puts "Global variable in FirstClass is #$globalvariable"
end
end
class SecondClass
def printglobal
puts "Global variable in SecondClass is #$globalvariable
end
end
class1obj = FirstClass.new
class1obj.printglobal
class2obj = SecondClass.new
class2obj.printglobal
Интермедиате Цоммандс
1. АКО… ЕЛСЕ у Руби-у
#!/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
2. Случај Руби
<#!/usr/bin/ruby
$age = 17
case $age
when 0 .. 17
puts "Not eligible to vote"
when > 17
puts "Eligible to vote"
else
puts "incorrect age"
end
3. Петље у Руби-у
- 3.1. Док је петља
#!/usr/bin/ruby
$i = 0
$num = 10
while $i <
$num do
puts("Inside the loop i = #$i" )
$i = $i + 1
end
- 3.2. До петље
#!/usr/bin/ruby
$i = 0
$num = 4
until $i > $num do
puts("Inside the loop i = #$i" )
$i = $i + 1;
end
- 3.3. За петљу
#!/usr/bin/ruby
for i in 0..9
puts "Local variable value is #(i)"
end
- 3.4. Изјава о прекиду
#!/usr/bin/ruby
for i in 0..5
if i > 3 then
break
end puts "Local variable is #(i)"
end
- 3.5. Следећа изјава
#!/usr/bin/ruby
for i in 0..10
if i < 6 then
next
end
puts "Local variable is #(i)"
end
4. Метода синтакса у Руби-у
#!/usr/bin/ruby
def test(a1 = "Noodles", a2 = "Pasta")
puts "The food is #(a1)"
puts "The food is #(a2)"
end
test "Burger", "Pizza"
test
5. Изјава о враћању у Руби
#!/usr/bin/ruby
def testreturn
a = 10
b = 20
c = 30
return a, b, c
endvar1 = testreturn
puts var1
6. Параметеризована метода у Руби-у
#!/usr/bin/ruby
def sample (*testparam)
puts "The number of parameters are #( testparam.length)"
for i in 0… testparam.length
puts "The parameters are #(testparam(i))"
end
end
sample "Hello", "123", "ABC", "Programming"
sample "World", "456", "Ruby"
7. Имплементацијски блок користећи изјаву о приносу
#!/usr/bin/ruby
def test
yield
end
test( puts "Hello world")
8. БЕГИН и ЕНД блокови у Руби-у
#!/usr/bin/ruby
BEGIN ( # BEGIN block code
puts "BEGIN code block"
)
END (
# END block code
puts "END code block"
)
# MAIN block code
puts "MAIN code block"
9. Гудачка експресија у Руби-у
#!/usr/bin/ruby
a, b, c = 1, 2, 3
puts "The value of a is #( a )."
puts "The sum of b and c is #( b + c )."
puts "The average is #( (a + b + c)/3 )."
10. Стварање низа у Руби-у
#!/usr/bin/ruby
names = Array.new(10)
puts names.size # returns 10
puts names.length # returns 10
Напредне Руби команде
1. Методе Геттер и Сеттер у Руби-у
#!/usr/bin/ruby -w
# defining a class
class Box
# constructor method
def initialize(l, b, h)
@length, @width, @height = l, b, h
end
# accessor methods
def printLength
@length
end
def printBreadth
@breadth
end
def printHeight
@height
end
end
# create
an object
box = Box.new(10, 30, 40)
# use accessor methods
l = box.printLength()
b = box.printBreadth()
h = box.printHeight()
puts "Box Length : #(l)"
puts "Box Breadth : #(b)"
puts “Box Height : #(h)”
2. Писање уобичајених скрипти интернетског пролаза користећи Руби
#!/usr/bin/ruby
"
require 'cgi'
cgi = CGI.new
puts cgi.header
puts "This is a test
3. Програмирање утичница помоћу Руби-ја
- 3.1. Једноставни пример сервера који користи Руби
require 'socket' # Get sockets from stdlib
server = TCPServer.open(8090) # listen on port 8090
loop ( # Running the server infinitely
client = server.accept # Connecting client wait time
client.puts(Time.now.ctime) # send time to client
client.puts "Closing the connection!"
client.close # Client disconnect
)
- 3.2. Једноставан пример клијента који користи Руби
require 'socket' # Get socket from stdlib
hostname = 'localhost' # Set hostname
port = 8090 # Set portsock = TCPSocket.open(hostname, port)
while line = sock.gets # Read lines from the socket
puts line.chop # print with platform line terminator
end
sock.close # Socket closing
4. Мултитхреадинг пример у Руби-у
#!/usr/bin/ruby
def function1
i = 0
while i<=2
puts "function1 at: #(Time.now)"
sleep(2) i = i+1
end
end
def function2
j = 0
while j<=2
puts "function2 at: #(Time.now)"
sleep(1)
j = j+1
end
end
puts "Started At #(Time.now)"
t1 = Thread.new(function1())
t2 = Thread.new(function2())
t1.join
t2.join
puts "End at #(Time.now)"
Савјети и трикови за кориштење Руби наредби
Будући да рад на било којем програмском језику захтева знање и спремност за надоградњу, ни овај случај није изузетак. Употреба основних наредби и вежбање и савладавање команди је кључ за савладавање овог лепог језика.
Закључак - Руби Команде
Руби команда је програмски језик слободног и отвореног кода; флексибилан је и богат значајкама. Као што име говори, рубин је заиста драгуљ који долази уз веома ниску цену уласка. Могућност укључивања и репродукције, као и лако читљива синтакса, чине га врло корисним. Његова напредна сценаристичка опрема такође резимира због своје популарности.
Препоручени чланци
Ово је водич за Руби команде. Овде смо разговарали о основним Руби командама и неким напредним Руби командама. Такође можете погледати следећи чланак да бисте сазнали више.
- Како се користе селенске наредбе?
- Врхунске команде за искре
- ХБасе команде
- Како се користе таблеау наредбе?
- Програмирање соцкет-а у Питхон-у