ruby intro {spection}
TRANSCRIPT
ChristianKakesa
https://twitter.com/christiankakesa
https://plus.google.com/+ChristianKakesa
RATP-SIT/CPS/SDP
WhatisRuby?WhousesRuby?RumorsaboutRubyWhyRuby?RubyforjavanerosRubyforphperosDeepinspection(part2-Rubytime)VirtualmachinesThelanguageUsageIdiomsEcosystemPracticewithRubyOnRailsLearnRuby
ProgramminglanguageCreatedbyYukihiroMatsumotoCreatedin1993(firstreleasein1995)Inspiredby:Smalltalk,Perl,Lisp,Python,...
puts"BecauseI'mhappy"BecauseI'mhappy=>nil
#Sum1,3,5,7,9,11,13[1,3,5,7,11,13].inject{|a,b|a+b}=>40
#Findthelengthofallthestrings["test","hellothere","how'slifetoday?"].collect{|string|string.length}=>[4,11,17]##or["test","hellothere","how'slifetoday?"].collect(&:length)=>[4,11,17]
== !=GarbagecollectorObjectsarestronglytypedMethodsencapsulation
publicprivateprotected
DocumentationRubydocJavadoc
PartofCfamily...
NocompilationNostatictypeNocastingNativethreadswithGILNoprimitives:
byte,short,int,long,float,double,boolean,char
...
== !=DynamicallytypedEvalLargestandardlibraryArraysandHashworkasexpectedHeredocs:'<<'or'<<-'(php:'<<<')PartofCfamily...
EverythingisanobjectNoabstractclassesorinterfacesbutmodulesAlmosteverythingisamethodcall:...
Crossplatform:GNU/Linux,Mac,Windows,BSD's,Solaris,...ObjectorientedVariablesarenottypedClasses,inheritanceandmixinsThreads(GILfornow)IteratorsandclosuresGarbagecollectionExceptionhandlingRegularexpressionsPowerfulstringoperationsOperatoroverloadingIntrospection,reflexion,metaprogrammingDucktypinglanguage...
NumericIntegerFloatsComplexRationalBigDecimal
String:'',"",+,character,...SymbolArrayHashBooleanNil:neutral,a ,notpresent
Set,Struct,...nnihilation
#Numeric1+1#=>21.+(1)#=>22.0**3#=>8.0Complex(2,3)#=>(2+3i)Rational(1)#=>(1/1)BigDecimal.new("1.0")/BigDecimal.new("0.0")#=>InfinityBigDecimal.new("-1.0")/BigDecimal.new("0.0")#=>-Infinity
#String,characterputs'I\'mHappy'#=>I'mHappybang='!'puts"I'mHappytoo#{bang}"#=>I'mHappytoo!puts'Hello'+'world'#=>Helloworldputs'ABCD'[1]#=>B
#Symbolf=:terms;s=:termsputsf.object_id#=>544328putss.object_id#=>544328
#Array,Hash[1,2,3,4,5,6]#=>[1,2,3,4,5,6]{f:42,s:4242}#=>{:f=>42,:s=>4242}
#Booleant=true#=>truet.class#=>TrueClassf=false#=>falsef.class#=>FalseClass
#ifexpressionmy_array=[]ifmy_array.empty?thenputs'Empty'end
res=42ifres==42puts"You'reright"endputs"You'reright"ifres==42
#unlessexpression(evaluate'false'or'nil')unlessres==42puts"You'rewrong"endputs"You'rewrong"unlessres==42puts"You'rewrong"ifnotres==42puts"You'rewrong"if!(res==42)
#if-elsif-elseexpressiona=[2,24,1,32,9,78]ifa.include?(42)puts"It'ssotrue"elsifa.empty?puts"I'mempty"elsifa.include?(nil)puts"Nilishere"elseputs'Nothingtodo'end
#ternaryoperatorputsres==42?"You'reright":"You'rewrong"##puts(ifres==42then"You'reright"else"You'rewrong"end)
#casewhens='127.0.0.1-srv[10/Oct/2000:13:55:36-0700]"GET/apache.gifHTTP/1.0"2002326'caseswhen/GET/puts"It'sanHTTPGETcommand"whenStringputs"Thisisastring"whenIntegerputs"Thisisainteger"when/^127.0.0.1/,/srv/puts"I'monthesamemachine"elseputs'Nothingtodo'end
#Loops:while,until,forina=[1,2,3,4,5]whilea.size>0#TrueClassprint"#{a.pop},"end#=>5,4,3,2,1,
a=[1,2,3,4,5]untila.empty?#FalseClassprint"#{a.pop},"end#=>5,4,3,2,1,
foriin1..5#Enumeratorprint"#{i},"end#=>1,2,3,4,5,
##next:gotothenextconditionforiin1..5#Enumeratornextifi<2print"#{i},"end#=>2,3,4,5,
##break:gooutoftheloopa=[1,2,3,4,5]untila.empty?#FalseClassbreakifa.size==2print"#{a.pop},"end#=>5,4,3,
#redo:onlythecurrentiteration(0..4).eachdo|i|puts"v:#{i}"redoifi>3end#v:0#v:1#v:2#v:3#v:4#v:4#...Infiniteloop..
#classclassMonkeyattr_reader:bananas#,...#defbananas#@bananas#end
attr_writer:mangos#,...#defmangos=(val)#@mangos=val#end
attr_accessor:papayas#,...#attr_reader:papayas#attr_writer:papayas
#Constructorisoptionaldefinitialize@bananas=42@@fruits=4242end
defmethod1#Dosomething...endend
m=Monkey.newm.method1
#classinheritanceclassMonkeyBis<Monkey#classmethoddefself.make_happyputs"I'mhappy"end#class<<self#defmake_happy#puts"I'mhappy"#end#defanother##...#end#endend
MonkeyBis.make_happy#=>I'mhappy
extendsinclude...
#begin,rescue,ensurebegin#..processf=File.open('42.txt','r')rescueIOError=>eputs'Errorhere!'rescue#..Allothererrorselseputs"Congratulations--noerrors!"ensuref.closeunlessf.nil?end
#raiseraiseraise"Thereissomethingwrong"##caller:HandlethestacktraceforthiserrorraiseCustomOrStandardException,"Failuremassage",Kernel::caller
#retry:restarttheentireblocofcodebeginforiin0..4puts"v:#{i}"raiseifi>2endrescueretryend#v:0#v:1#v:2#v:3#v:0#...Infiniteloop..
#Lambda,numberofparametersmustmatch!defmeth#my_lambda=->{return"I'msick"}my_lambda=lambda{return"I'msick"}my_lambda.call
return"I'mOK"end
putsmeth#=>I'mOK
#Proc,'return'fromthemethodandnottheprocdefmeth#my_proc=proc{return"I'msick"}my_proc=Proc.new{return"I'msick"}my_proc.call
return"I'mOK"end
putsmeth#=>I'msick
#Onelinecomment
=beginBlocofcommentdefmeth#my_lambda=->{return"I'msick"}my_lambda=lambda{return"I'msick"}my_lambda.callreturn"I'mOK"end=end
classPersondeftalkputs'Lassmichinruhe!'endend#Person.new().talk()Person.new.talk#=>Lassmichinruhe!
classPersondeftalkputs'Lassmichinruhe!';puts'Writecorrectly!';puts'Thisisgood!'endendPerson.new.talk#=>Lassmichinruhe!#=>Writecorrectly!#=>Thisisgood!
#'?':MethodreturningabooleanvalueclassUserdefis_admin?falseendend
user=User.newputs"I'mnotanadmin"unlessuser.is_admin?#=>I'mnotanadmin
#'!':Dangerousmethod,preventthedeveloperclassUser#...
defadmin_protect!exit42unlessself.is_admin?puts'Somethingelse'endend
user=User.newuser.admin_protect!#=>//Exittheprogramme
1.is_a?Object#=>true1.class#=>FixnumFixnum.is_a?Object#=>true''.class#=>String
#send##"uppercaseme".upcaseputs"uppercaseme".send(:upcase)#=>UPPERCASEME
#instancevariableclassVars;endv=Vars.new{var1:1,var2:2}.eachdo|name,value|v.instance_variable_set("@#{name}",value)end
puts"var1:#{v.instance_variable_get('@var1')}"puts"var2:#{v.instance_variable_get('@var2')}"#=>var1:1#=>var2:2
#class_eval
classGuess#definitialize#@what=42#end
#defwhat#@what#endend
Guess.class_eval('definitialize;@what=42;end')Guess.class_eval{defwhat;@what;end}
Guess.what#=>NoMethodError:undefinedmethod`what'forMonk:Class...
g=Guess.newputsg.what#=>42
#instance_eval
classPerson#defself.human?#true#endend
Person.instance_evaldodefhuman?trueendend
putsPerson.human??'Yes':'No'#=>Yes
#More:eval,module_eval,define_method,...
#WindowsManagementIntrumentation##ListallUSBdevicesrequire'win32ole'
wmi=WIN32OLE.connect("winmgmts://")
devices=wmi.ExecQuery("Select*FromWin32_USBControllerDevice")fordeviceindevicesdodevice_name=device.Dependent.gsub('"','').split('=')[1]usb_devices=wmi.ExecQuery("Select*FromWin32_PnPEntityWhereDeviceID='#{device_name}'")forusb_deviceinusb_devicesdoputsusb_device.Descriptionifusb_device.Description=='USBMassStorageDevice'#DOSOMETHINGHEREendendend
#RegistryaccessorlibraryforWindowsrequire'win32/registry'keyname='SYSTEM\\CurrentControlSet\\Control\\SessionManager\\Environment'
#KEY_ALL_ACCESSenablesyoutowriteanddeleted.#thedefaultaccessisKEY_READifyouspecifynothingaccess=Win32::Registry::KEY_ALL_ACCESS
Win32::Registry::HKEY_LOCAL_MACHINE.open(keyname,access)do|reg|#eachisthesameaseach_value,because#each_keyactuallymeans#"eachchildfolder"so#eachdoesn'tlistanychildfolders...#use#keysforthat...reg.each{|name,value|putsname,value}end
[1,2,3].map{|x|2*x}#=>[2,4,6]##singlelineor'do..end'
[1,2,3].mapdo|x|2*xend
unlessdone#multiplelines...end
if!done#multiplelines...end#orifnotdone#multiplelines...end
ifdonesingle_expresion_or_methodend
single_expresion_or_methodifdone
putsmy_value.to_sifmy_value if!my_value.nil?putsmy_value.to_send
Rubygems:RubypackageBundler:Manageapplication'sgemsdependencies
:Rack,Rake,ActiveRecord,Brakeman,...RVM,Rbenv:RubyversionmanagerPuppet, :Configurationmanagementfor
:Deploymanagementutility:Testingtool
Rdoc:Rubydocumentation:securitytestingtool,
...
geminstallrailsrailsnewsdp_blogcdsdp_blograilsserver
railsgeneratecontrollerhomeindex
#config/route.rb#...#root'home#index'#...
railsgeneratescaffoldArticletitle:stringdescription:textrakedb:migrate
#Addatwitterbootstrapgemin'Gemfile'#gem'bootstrap-sass','~>3.3.0'
#AddBootstrapinproject##app/assets/stylesheets/application.css.scss#@import"bootstrap-sprockets";#@import"bootstrap";
##app/assets/javascripts/application.js#...#//=requirebootstrap-sprockets#...
IRB(REPL)Rubyin20minutes:TryRuby(onlineRubyconsole):Rubywarrior, :Codecademy:
English:French:
https://www.ruby-lang.org/en/documentation/quickstart/
http://tryruby.org/https://www.bloc.io/ruby-warrior
http://www.codecademy.com/glossary/rubyhttp://www.codecademy.com/fr/glossary/ruby