SlideShare a Scribd company logo
Learn RUBY Programming at
AMC Square Learning
•An interpreted language
• a.k.a dynamic, scripting
• e.g., Perl
•Object Oriented
• Single inheritance
•High level
• Good support for system calls, regex and CGI
•Relies heavily on convention for syntax
Hello World
#!/usr/bin/env ruby
puts “Hello world”
$ chmod a+x helloWorld.rb
$ helloWorld.rb
Hello world
$
• shell script directive to run ruby
• Needed to run any shell script
• Call to method puts to write out
“Hello world” with CR
• Make program executable
Basic Ruby
•Everything is an object
•Variables are not typed
•Automatic memory allocation and garbage
collection
•Comments start with # and go to the end of the line
• You have to escape # if you want them elsewhere
•Carriage returns mark the end of statements
•Methods marked with def … end
Control structures
If…elsif…else…end
case when <condition> then
<value>… else… end
unless <condition> … end
while <condition>… end
until <condition>… end
#.times (e.g. 5.times())
#.upto(#) (e.g. 3.upto(6))
<collection>.each {block}
• elsif keeps blocks at same level
• case good for checks on multiple
values of same expression; can use
ranges
grade = case score
when 90..100 then “A”
when 80..90 then “B”
else “C”
end
• Looping constructs use end (same as
class definitions)
• Various iterators allow code blocks to
be run multiple times
Ruby Naming Conventions
• Initial characters
• Local variables, method parameters, and method names 
lowercase letter or underscore
• Global variable  $
• Instance variable  @
• Class variable  @@
• Class names, module names, constants  uppercase letter
• Multi-word names
• Instance variables  separate words with underscores
• Class names  use MixedCase
• End characters
• ? Indicates method that returns true or false to a query
• ! Indicates method that modifies the object in place rather than
returning a copy (destructive, but usually more efficient)
Another Example
class Temperature
Factor = 5.0/9
def store_C(c)
@celsius = c
end
def store_F(f)
@celsius = (f - 32)*Factor
end
def as_C
@celsius
end
def as_F
(@celsius / Factor) + 32
end
end # end of class definition
Factor is a constant
5.0 makes it a float
4 methods that get/set an
instance variable
Last evaluated statement is
considered the return
value
Second Try
class Temperature
Factor = 5.0/9
attr_accessor :c
def f=(f)
@c = (f - 32) * Factor
end
def f
(@c / Factor) + 32
end
def initialize (c)
@c = c
end
end
t = Temperature.new(25)
puts t.f # 77.0
t.f = 60 # invokes f=()
puts t.c # 15.55
attr_accessor creates setter and
getter methods automatically for a
class variable
initialize is the name for a
classes’ constructor
Don’t worry - you can always override
these methods if you need to
Calls to methods don’t need () if
unambiguous
Input and Output - tsv files
f = File.open ARGV[0]
while ! f.eof?
line = f.gets
if line =~ /^#/
next
elsif line =~ /^s*$/
next
else
puts line
end
end
f.close
ARGV is a special array
holding the command-
line tokens
Gets a line
If it’s not a comment or a
blank line
Print it
Processing TSV filesh = Hash.new
f = File.open ARGV[0]
while ! f.eof?
line = f.gets.chomp
if line =~ /^#/
next
elsif line =~ /^s*$/
next
else
tokens = line.split /t/
h[tokens[2]] = tokens[1]
end
end
f.close
keys =
h.keys.sort {|a,b| a <=> b}
keys.each {|k|
puts "#{k}t#{h[k]}" }
Declare a hash table
Get lines without n or rn - chomp
split lines into fields delimited with tabs
Store some data from each field into the
hash
Sort the keys - sort method takes a block
of code as input
each creates an iterator in which k is set
to a value at each pass
#{…} outputs the evaluated expression in
the double quoted string
Blocks
•Allow passing chunks of code in to methods
•Receiving method uses “yield” command to call
passed code (can call yield multiple times)
•Single line blocks enclosed in {}
•Multi-line blocks enclosed in do…end
•Can use parameters
[ 1, 3, 4, 7, 9 ].each {|i| puts i }
Keys = h.keys.sort {|a,b| a <=> b }
Running system commands
require 'find'
Find.find('.') do
|filename|
if filename =~ /.txt$/i
url_output =
filename.gsub(/.txt$/i, ".html")
url = `cat #{filename}`.chomp
cmd = "curl #{url} -o #{url_output}";
puts cmd
`#{cmd}`
end
end
• require reads in another
ruby file - in this case a
module called Find
• Find returns an array, we
create an iterator filename
to go thru its instances
• We create a new variable to
hold a new filename with the
same base but different .html
extension
• We use backticks `` to run a
system command and
(optionally) save the output
into a variable
• curl is a command in mac os to
retrieve a URL to a file, like wget in
unix
CGI example
require 'cgi'
cgi = CGI.new("html3")
size = cgi.params.size
if size > 0 # processing form
in = cgi.params['t'].first.untaint
cgi.out { cgi.html { cgi.head
cgi.body { "Welcome, #{in}!" }
} }
else
puts <<FORM
Content-type: text/html
<HTML><BODY><FORM>
Enter your name: <INPUT TYPE=TEXT
NAME=t><INPUT TYPE=SUBMIT>
</FORM></BODY></HTML>
FORM
end
• CGI requires library
• Create CGI object
• If parameters passed
• Process variable t
• untaint variables if using
them in commands
• No parameters?
• create form using here
document “<<“
Reflection
...to examine aspects of the program from within the program itself.
#print out all of the objects in our system
ObjectSpace.each_object(Class) {|c| puts c}
#Get all the methods on an object
“Some String”.methods
#see if an object responds to a certain method
obj.respond_to?(:length)
#see if an object is a type
obj.kind_of?(Numeric)
obj.instance_of?(FixNum)
Thank You

More Related Content

What's hot (20)

PDF
Klee and angr
Wei-Bo Chen
 
PDF
CNIT 127: Ch 2: Stack overflows on Linux
Sam Bowne
 
PPTX
Python Programming Essentials - M25 - os and sys modules
P3 InfoTech Solutions Pvt. Ltd.
 
PDF
CNIT 127: Ch 3: Shellcode
Sam Bowne
 
PPTX
Unix shell scripts
Prakash Lambha
 
PPTX
Python
Wei-Bo Chen
 
PDF
scala-gopher: async implementation of CSP for scala
Ruslan Shevchenko
 
PPTX
Shell programming 1.ppt
Kalkey
 
PDF
Triton and symbolic execution on gdb
Wei-Bo Chen
 
PDF
CNIT 127 Ch 1: Before you Begin
Sam Bowne
 
PDF
Defer, Panic, Recover
Joris Bonnefoy
 
PDF
Clojure+ClojureScript Webapps
Falko Riemenschneider
 
PPTX
Unix - Shell Scripts
ananthimurugesan
 
PDF
Unix Tutorial
Sanjay Saluth
 
PPTX
x86
Wei-Bo Chen
 
PDF
Go Lang Tutorial
Wei-Ning Huang
 
PPTX
Go Programming Language (Golang)
Ishin Vin
 
PPTX
Golang iran - tutorial go programming language - Preliminary
go-lang
 
PDF
A closure ekon16
Max Kleiner
 
PPTX
Clojure 7-Languages
Pierre de Lacaze
 
Klee and angr
Wei-Bo Chen
 
CNIT 127: Ch 2: Stack overflows on Linux
Sam Bowne
 
Python Programming Essentials - M25 - os and sys modules
P3 InfoTech Solutions Pvt. Ltd.
 
CNIT 127: Ch 3: Shellcode
Sam Bowne
 
Unix shell scripts
Prakash Lambha
 
Python
Wei-Bo Chen
 
scala-gopher: async implementation of CSP for scala
Ruslan Shevchenko
 
Shell programming 1.ppt
Kalkey
 
Triton and symbolic execution on gdb
Wei-Bo Chen
 
CNIT 127 Ch 1: Before you Begin
Sam Bowne
 
Defer, Panic, Recover
Joris Bonnefoy
 
Clojure+ClojureScript Webapps
Falko Riemenschneider
 
Unix - Shell Scripts
ananthimurugesan
 
Unix Tutorial
Sanjay Saluth
 
Go Lang Tutorial
Wei-Ning Huang
 
Go Programming Language (Golang)
Ishin Vin
 
Golang iran - tutorial go programming language - Preliminary
go-lang
 
A closure ekon16
Max Kleiner
 
Clojure 7-Languages
Pierre de Lacaze
 

Similar to Learn Ruby Programming in Amc Square Learning (20)

PPTX
Ruby -the wheel Technology
ppparthpatel123
 
KEY
Ruby
Kerry Buckley
 
PDF
Introduction to Ruby
MobME Technical
 
PPTX
Ruby Basics
NagaLakshmi_N
 
PDF
Ruby training day1
Bindesh Vijayan
 
PDF
Ruby_Basic
Kushal Jangid
 
KEY
Introducing Ruby
James Thompson
 
PPT
name name2 n2.ppt
callroom
 
PPT
name name2 n
callroom
 
PPT
name name2 n2
callroom
 
PPT
name name2 n
callroom
 
PPT
ppt18
callroom
 
PPT
ppt9
callroom
 
PPT
name name2 n
callroom
 
PPT
ppt7
callroom
 
PPT
ppt30
callroom
 
PPT
ppt21
callroom
 
PPT
ppt2
callroom
 
PPT
ppt17
callroom
 
PPT
test ppt
callroom
 
Ruby -the wheel Technology
ppparthpatel123
 
Introduction to Ruby
MobME Technical
 
Ruby Basics
NagaLakshmi_N
 
Ruby training day1
Bindesh Vijayan
 
Ruby_Basic
Kushal Jangid
 
Introducing Ruby
James Thompson
 
name name2 n2.ppt
callroom
 
name name2 n
callroom
 
name name2 n2
callroom
 
name name2 n
callroom
 
ppt18
callroom
 
ppt9
callroom
 
name name2 n
callroom
 
ppt7
callroom
 
ppt30
callroom
 
ppt21
callroom
 
ppt2
callroom
 
ppt17
callroom
 
test ppt
callroom
 
Ad

More from ASIT Education (20)

PPTX
COMMON PROBLEMS FACING WITH TABLETS
ASIT Education
 
PPTX
Simple hardware problems facing in pc's
ASIT Education
 
DOCX
Amc square IT services
ASIT Education
 
PPT
learn JAVA at ASIT with a placement assistance.
ASIT Education
 
PPT
Learn my sql at amc square learning
ASIT Education
 
PPT
Learn joomla at amc square learning
ASIT Education
 
PPT
learn ANDROID at AMC Square Learning
ASIT Education
 
PPT
Learn spring at amc square learning
ASIT Education
 
PPT
Learn cpp at amc square learning
ASIT Education
 
PPT
Learn perl in amc square learning
ASIT Education
 
PPT
Learn c sharp at amc square learning
ASIT Education
 
PPT
learn sharepoint at AMC Square learning
ASIT Education
 
PPT
Introduction to software testing
ASIT Education
 
PPTX
C programmimng basic.ppt
ASIT Education
 
PPT
Introduction to vm ware
ASIT Education
 
PPT
Introduction to software testing
ASIT Education
 
PPT
Introduction to phython programming
ASIT Education
 
PPT
Introduction to java programming
ASIT Education
 
PPTX
Introduction to internet
ASIT Education
 
PPTX
Android
ASIT Education
 
COMMON PROBLEMS FACING WITH TABLETS
ASIT Education
 
Simple hardware problems facing in pc's
ASIT Education
 
Amc square IT services
ASIT Education
 
learn JAVA at ASIT with a placement assistance.
ASIT Education
 
Learn my sql at amc square learning
ASIT Education
 
Learn joomla at amc square learning
ASIT Education
 
learn ANDROID at AMC Square Learning
ASIT Education
 
Learn spring at amc square learning
ASIT Education
 
Learn cpp at amc square learning
ASIT Education
 
Learn perl in amc square learning
ASIT Education
 
Learn c sharp at amc square learning
ASIT Education
 
learn sharepoint at AMC Square learning
ASIT Education
 
Introduction to software testing
ASIT Education
 
C programmimng basic.ppt
ASIT Education
 
Introduction to vm ware
ASIT Education
 
Introduction to software testing
ASIT Education
 
Introduction to phython programming
ASIT Education
 
Introduction to java programming
ASIT Education
 
Introduction to internet
ASIT Education
 
Ad

Recently uploaded (20)

PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PDF
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PDF
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 

Learn Ruby Programming in Amc Square Learning

  • 1. Learn RUBY Programming at AMC Square Learning •An interpreted language • a.k.a dynamic, scripting • e.g., Perl •Object Oriented • Single inheritance •High level • Good support for system calls, regex and CGI •Relies heavily on convention for syntax
  • 2. Hello World #!/usr/bin/env ruby puts “Hello world” $ chmod a+x helloWorld.rb $ helloWorld.rb Hello world $ • shell script directive to run ruby • Needed to run any shell script • Call to method puts to write out “Hello world” with CR • Make program executable
  • 3. Basic Ruby •Everything is an object •Variables are not typed •Automatic memory allocation and garbage collection •Comments start with # and go to the end of the line • You have to escape # if you want them elsewhere •Carriage returns mark the end of statements •Methods marked with def … end
  • 4. Control structures If…elsif…else…end case when <condition> then <value>… else… end unless <condition> … end while <condition>… end until <condition>… end #.times (e.g. 5.times()) #.upto(#) (e.g. 3.upto(6)) <collection>.each {block} • elsif keeps blocks at same level • case good for checks on multiple values of same expression; can use ranges grade = case score when 90..100 then “A” when 80..90 then “B” else “C” end • Looping constructs use end (same as class definitions) • Various iterators allow code blocks to be run multiple times
  • 5. Ruby Naming Conventions • Initial characters • Local variables, method parameters, and method names  lowercase letter or underscore • Global variable  $ • Instance variable  @ • Class variable  @@ • Class names, module names, constants  uppercase letter • Multi-word names • Instance variables  separate words with underscores • Class names  use MixedCase • End characters • ? Indicates method that returns true or false to a query • ! Indicates method that modifies the object in place rather than returning a copy (destructive, but usually more efficient)
  • 6. Another Example class Temperature Factor = 5.0/9 def store_C(c) @celsius = c end def store_F(f) @celsius = (f - 32)*Factor end def as_C @celsius end def as_F (@celsius / Factor) + 32 end end # end of class definition Factor is a constant 5.0 makes it a float 4 methods that get/set an instance variable Last evaluated statement is considered the return value
  • 7. Second Try class Temperature Factor = 5.0/9 attr_accessor :c def f=(f) @c = (f - 32) * Factor end def f (@c / Factor) + 32 end def initialize (c) @c = c end end t = Temperature.new(25) puts t.f # 77.0 t.f = 60 # invokes f=() puts t.c # 15.55 attr_accessor creates setter and getter methods automatically for a class variable initialize is the name for a classes’ constructor Don’t worry - you can always override these methods if you need to Calls to methods don’t need () if unambiguous
  • 8. Input and Output - tsv files f = File.open ARGV[0] while ! f.eof? line = f.gets if line =~ /^#/ next elsif line =~ /^s*$/ next else puts line end end f.close ARGV is a special array holding the command- line tokens Gets a line If it’s not a comment or a blank line Print it
  • 9. Processing TSV filesh = Hash.new f = File.open ARGV[0] while ! f.eof? line = f.gets.chomp if line =~ /^#/ next elsif line =~ /^s*$/ next else tokens = line.split /t/ h[tokens[2]] = tokens[1] end end f.close keys = h.keys.sort {|a,b| a <=> b} keys.each {|k| puts "#{k}t#{h[k]}" } Declare a hash table Get lines without n or rn - chomp split lines into fields delimited with tabs Store some data from each field into the hash Sort the keys - sort method takes a block of code as input each creates an iterator in which k is set to a value at each pass #{…} outputs the evaluated expression in the double quoted string
  • 10. Blocks •Allow passing chunks of code in to methods •Receiving method uses “yield” command to call passed code (can call yield multiple times) •Single line blocks enclosed in {} •Multi-line blocks enclosed in do…end •Can use parameters [ 1, 3, 4, 7, 9 ].each {|i| puts i } Keys = h.keys.sort {|a,b| a <=> b }
  • 11. Running system commands require 'find' Find.find('.') do |filename| if filename =~ /.txt$/i url_output = filename.gsub(/.txt$/i, ".html") url = `cat #{filename}`.chomp cmd = "curl #{url} -o #{url_output}"; puts cmd `#{cmd}` end end • require reads in another ruby file - in this case a module called Find • Find returns an array, we create an iterator filename to go thru its instances • We create a new variable to hold a new filename with the same base but different .html extension • We use backticks `` to run a system command and (optionally) save the output into a variable • curl is a command in mac os to retrieve a URL to a file, like wget in unix
  • 12. CGI example require 'cgi' cgi = CGI.new("html3") size = cgi.params.size if size > 0 # processing form in = cgi.params['t'].first.untaint cgi.out { cgi.html { cgi.head cgi.body { "Welcome, #{in}!" } } } else puts <<FORM Content-type: text/html <HTML><BODY><FORM> Enter your name: <INPUT TYPE=TEXT NAME=t><INPUT TYPE=SUBMIT> </FORM></BODY></HTML> FORM end • CGI requires library • Create CGI object • If parameters passed • Process variable t • untaint variables if using them in commands • No parameters? • create form using here document “<<“
  • 13. Reflection ...to examine aspects of the program from within the program itself. #print out all of the objects in our system ObjectSpace.each_object(Class) {|c| puts c} #Get all the methods on an object “Some String”.methods #see if an object responds to a certain method obj.respond_to?(:length) #see if an object is a type obj.kind_of?(Numeric) obj.instance_of?(FixNum)