defblock_testputs"We're in the method!"puts"Yielding to the block..."yieldputs"We're back in the method!"endblock_test{puts">>> We're in the block!"}#you can pass parameter toodefyield_name(name)puts"In the method! Let's yield."yieldnameputs"Block complete! Back in the method."endyield_name("samuel"){|a|puts"My name is #{a}."}
The output is
We're in the method!
Yielding to the block...
>>> We're in the block!
We're back in the method!
In the method! Let's yield.
My name is samuel.
Block complete! Back in the method.
Why Proc?
block can’t be saved to a variable and not a regular object. Proc keep your code reusable. With blocks you have to write your code out each time you need it.
With proc, you write your code once. Proc is savable block.
12345678910
floats=[1.2,3.45,0.91,7.727,11.42,482.911]round_down=Proc.new{|x|x.floor}# & is used to convert round_down proc to blockints=floats.collect(&round_down)# [1, 3, 0, 7, 11, 482]# you can call proc directlyround_down.call(10.45)# 10# convert Symbol to Proc by &putsfloats.map(&:to_s)
Lambdas checks the number of arguments passed to it. Procs ignore it.
When Lambdas returns, it passes control back to calling method. Procs doesn’t
123456789101112131415
defbatman_ironman_procvictor=Proc.new{return"Batman will win!"}victor.call"Iron Man will win!"endputsbatman_ironman_proc# Batman will win!defbatman_ironman_lambdavictor=lambda{return"Batman will win!"}victor.call"Iron Man will win!"endputsbatman_ironman_lambda# Iron Man will win!
Class
Object-Oriented language always has class. def initialize就相當於constructor
classPerson$type="human"@@other="other info"definitialize(name)@name=nameenddefgetMe@nameenddefself.getOther@@otherendendman=Person.new("samuel")puts$type# humanputsman.getMe# samuelputsPerson.getOther# other info
module is like class but it can’t create instance and submodule
123456789101112131415161718192021
moduleMyModule#constant variableNAME="samuel"#class methoddefself.showFullputsNAME+" hung"endend# user :: to access variableputsMyModule::NAME# samuelMyModule.showFull# samuel hung# you can use include to get module scopeincludeMyModuleputsNAME# samuelshowFull# this line will cause error, you can't do this on method even you change the scope.# load other module to userequire'date'putsDate.today