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

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

What's hot (20)

Klee and angr
Klee and angrKlee and angr
Klee and angr
 
CNIT 127: Ch 2: Stack overflows on Linux
CNIT 127: Ch 2: Stack overflows on LinuxCNIT 127: Ch 2: Stack overflows on Linux
CNIT 127: Ch 2: Stack overflows on Linux
 
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesPython Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modules
 
CNIT 127: Ch 3: Shellcode
CNIT 127: Ch 3: ShellcodeCNIT 127: Ch 3: Shellcode
CNIT 127: Ch 3: Shellcode
 
Unix shell scripts
Unix shell scriptsUnix shell scripts
Unix shell scripts
 
Python
PythonPython
Python
 
scala-gopher: async implementation of CSP for scala
scala-gopher:  async implementation of CSP  for  scalascala-gopher:  async implementation of CSP  for  scala
scala-gopher: async implementation of CSP for scala
 
Shell programming 1.ppt
Shell programming  1.pptShell programming  1.ppt
Shell programming 1.ppt
 
Triton and symbolic execution on gdb
Triton and symbolic execution on gdbTriton and symbolic execution on gdb
Triton and symbolic execution on gdb
 
CNIT 127 Ch 1: Before you Begin
CNIT 127 Ch 1: Before you BeginCNIT 127 Ch 1: Before you Begin
CNIT 127 Ch 1: Before you Begin
 
Defer, Panic, Recover
Defer, Panic, RecoverDefer, Panic, Recover
Defer, Panic, Recover
 
Clojure+ClojureScript Webapps
Clojure+ClojureScript WebappsClojure+ClojureScript Webapps
Clojure+ClojureScript Webapps
 
Unix - Shell Scripts
Unix - Shell ScriptsUnix - Shell Scripts
Unix - Shell Scripts
 
Unix Tutorial
Unix TutorialUnix Tutorial
Unix Tutorial
 
x86
x86x86
x86
 
Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
 
Golang iran - tutorial go programming language - Preliminary
Golang iran - tutorial  go programming language - PreliminaryGolang iran - tutorial  go programming language - Preliminary
Golang iran - tutorial go programming language - Preliminary
 
A closure ekon16
A closure ekon16A closure ekon16
A closure ekon16
 
Clojure 7-Languages
Clojure 7-LanguagesClojure 7-Languages
Clojure 7-Languages
 

Similar to Learn Ruby Programming in Amc Square Learning

shellScriptAlt.pptx
shellScriptAlt.pptxshellScriptAlt.pptx
shellScriptAlt.pptx
NiladriDey18
 
Designing Ruby APIs
Designing Ruby APIsDesigning Ruby APIs
Designing Ruby APIs
Wen-Tien Chang
 
Mastering unix
Mastering unixMastering unix
Mastering unixRaghu nath
 
ITB_2023_CommandBox_Task_Runners_Brad_Wood.pdf
ITB_2023_CommandBox_Task_Runners_Brad_Wood.pdfITB_2023_CommandBox_Task_Runners_Brad_Wood.pdf
ITB_2023_CommandBox_Task_Runners_Brad_Wood.pdf
Ortus Solutions, Corp
 
The why and how of moving to php 5.4/5.5
The why and how of moving to php 5.4/5.5The why and how of moving to php 5.4/5.5
The why and how of moving to php 5.4/5.5
Wim Godden
 
Preparing for the next PHP version (5.6)
Preparing for the next PHP version (5.6)Preparing for the next PHP version (5.6)
Preparing for the next PHP version (5.6)
Damien Seguy
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot Camp
Troy Miles
 
C#unit4
C#unit4C#unit4
C#unit4
raksharao
 
Course 102: Lecture 8: Composite Commands
Course 102: Lecture 8: Composite Commands Course 102: Lecture 8: Composite Commands
Course 102: Lecture 8: Composite Commands
Ahmed El-Arabawy
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest UpdatesIftekhar Eather
 
Shell Script Tutorial
Shell Script TutorialShell Script Tutorial
Shell Script Tutorial
Quang Minh Đoàn
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell ScriptingRaghu nath
 
Learning Puppet basic thing
Learning Puppet basic thing Learning Puppet basic thing
Learning Puppet basic thing
DaeHyung Lee
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
Ashrith Mekala
 
React Native One Day
React Native One DayReact Native One Day
React Native One Day
Troy Miles
 
Licão 13 functions
Licão 13 functionsLicão 13 functions
Licão 13 functions
Acácio Oliveira
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
Tushar Pal
 

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

shellScriptAlt.pptx
shellScriptAlt.pptxshellScriptAlt.pptx
shellScriptAlt.pptx
 
Gun make
Gun makeGun make
Gun make
 
Shell Scripting
Shell ScriptingShell Scripting
Shell Scripting
 
Designing Ruby APIs
Designing Ruby APIsDesigning Ruby APIs
Designing Ruby APIs
 
Mastering unix
Mastering unixMastering unix
Mastering unix
 
ITB_2023_CommandBox_Task_Runners_Brad_Wood.pdf
ITB_2023_CommandBox_Task_Runners_Brad_Wood.pdfITB_2023_CommandBox_Task_Runners_Brad_Wood.pdf
ITB_2023_CommandBox_Task_Runners_Brad_Wood.pdf
 
The why and how of moving to php 5.4/5.5
The why and how of moving to php 5.4/5.5The why and how of moving to php 5.4/5.5
The why and how of moving to php 5.4/5.5
 
Preparing for the next PHP version (5.6)
Preparing for the next PHP version (5.6)Preparing for the next PHP version (5.6)
Preparing for the next PHP version (5.6)
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot Camp
 
Slides
SlidesSlides
Slides
 
C#unit4
C#unit4C#unit4
C#unit4
 
Course 102: Lecture 8: Composite Commands
Course 102: Lecture 8: Composite Commands Course 102: Lecture 8: Composite Commands
Course 102: Lecture 8: Composite Commands
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
 
Shell Script Tutorial
Shell Script TutorialShell Script Tutorial
Shell Script Tutorial
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell Scripting
 
Learning Puppet basic thing
Learning Puppet basic thing Learning Puppet basic thing
Learning Puppet basic thing
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
 
React Native One Day
React Native One DayReact Native One Day
React Native One Day
 
Licão 13 functions
Licão 13 functionsLicão 13 functions
Licão 13 functions
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 

More from ASIT Education

COMMON PROBLEMS FACING WITH TABLETS
COMMON PROBLEMS FACING WITH TABLETSCOMMON PROBLEMS FACING WITH TABLETS
COMMON PROBLEMS FACING WITH TABLETS
ASIT Education
 
Simple hardware problems facing in pc's
Simple hardware problems facing in pc'sSimple hardware problems facing in pc's
Simple hardware problems facing in pc's
ASIT Education
 
Amc square IT services
Amc square IT servicesAmc square IT services
Amc square IT services
ASIT Education
 
learn JAVA at ASIT with a placement assistance.
learn JAVA at ASIT with a placement assistance.learn JAVA at ASIT with a placement assistance.
learn JAVA at ASIT with a placement assistance.
ASIT Education
 
Learn my sql at amc square learning
Learn my sql at amc square learningLearn my sql at amc square learning
Learn my sql at amc square learning
ASIT Education
 
Learn joomla at amc square learning
Learn joomla at amc square learningLearn joomla at amc square learning
Learn joomla at amc square learning
ASIT Education
 
learn ANDROID at AMC Square Learning
learn ANDROID at AMC Square Learninglearn ANDROID at AMC Square Learning
learn ANDROID at AMC Square Learning
ASIT Education
 
Learn spring at amc square learning
Learn spring at amc square learningLearn spring at amc square learning
Learn spring at amc square learning
ASIT Education
 
Learn cpp at amc square learning
Learn cpp at amc square learningLearn cpp at amc square learning
Learn cpp at amc square learning
ASIT Education
 
Learn perl in amc square learning
Learn perl in amc square learningLearn perl in amc square learning
Learn perl in amc square learning
ASIT Education
 
Learn c sharp at amc square learning
Learn c sharp at amc square learningLearn c sharp at amc square learning
Learn c sharp at amc square learning
ASIT Education
 
learn sharepoint at AMC Square learning
learn sharepoint at AMC Square learninglearn sharepoint at AMC Square learning
learn sharepoint at AMC Square learning
ASIT Education
 
Introduction to software testing
Introduction to software testingIntroduction to software testing
Introduction to software testing
ASIT Education
 
C programmimng basic.ppt
C programmimng basic.pptC programmimng basic.ppt
C programmimng basic.ppt
ASIT Education
 
Introduction to vm ware
Introduction to vm wareIntroduction to vm ware
Introduction to vm ware
ASIT Education
 
Introduction to software testing
Introduction to software testingIntroduction to software testing
Introduction to software testing
ASIT Education
 
Introduction to phython programming
Introduction to phython programmingIntroduction to phython programming
Introduction to phython programming
ASIT Education
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programming
ASIT Education
 
Introduction to internet
Introduction to internetIntroduction to internet
Introduction to internet
ASIT Education
 
Android
AndroidAndroid

More from ASIT Education (20)

COMMON PROBLEMS FACING WITH TABLETS
COMMON PROBLEMS FACING WITH TABLETSCOMMON PROBLEMS FACING WITH TABLETS
COMMON PROBLEMS FACING WITH TABLETS
 
Simple hardware problems facing in pc's
Simple hardware problems facing in pc'sSimple hardware problems facing in pc's
Simple hardware problems facing in pc's
 
Amc square IT services
Amc square IT servicesAmc square IT services
Amc square IT services
 
learn JAVA at ASIT with a placement assistance.
learn JAVA at ASIT with a placement assistance.learn JAVA at ASIT with a placement assistance.
learn JAVA at ASIT with a placement assistance.
 
Learn my sql at amc square learning
Learn my sql at amc square learningLearn my sql at amc square learning
Learn my sql at amc square learning
 
Learn joomla at amc square learning
Learn joomla at amc square learningLearn joomla at amc square learning
Learn joomla at amc square learning
 
learn ANDROID at AMC Square Learning
learn ANDROID at AMC Square Learninglearn ANDROID at AMC Square Learning
learn ANDROID at AMC Square Learning
 
Learn spring at amc square learning
Learn spring at amc square learningLearn spring at amc square learning
Learn spring at amc square learning
 
Learn cpp at amc square learning
Learn cpp at amc square learningLearn cpp at amc square learning
Learn cpp at amc square learning
 
Learn perl in amc square learning
Learn perl in amc square learningLearn perl in amc square learning
Learn perl in amc square learning
 
Learn c sharp at amc square learning
Learn c sharp at amc square learningLearn c sharp at amc square learning
Learn c sharp at amc square learning
 
learn sharepoint at AMC Square learning
learn sharepoint at AMC Square learninglearn sharepoint at AMC Square learning
learn sharepoint at AMC Square learning
 
Introduction to software testing
Introduction to software testingIntroduction to software testing
Introduction to software testing
 
C programmimng basic.ppt
C programmimng basic.pptC programmimng basic.ppt
C programmimng basic.ppt
 
Introduction to vm ware
Introduction to vm wareIntroduction to vm ware
Introduction to vm ware
 
Introduction to software testing
Introduction to software testingIntroduction to software testing
Introduction to software testing
 
Introduction to phython programming
Introduction to phython programmingIntroduction to phython programming
Introduction to phython programming
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programming
 
Introduction to internet
Introduction to internetIntroduction to internet
Introduction to internet
 
Android
AndroidAndroid
Android
 

Recently uploaded

Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 

Recently uploaded (20)

Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 

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)