国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

rails圣經總結

2019-11-08 18:42:00
字體:
來源:轉載
供稿:網友

rails圣經總結

方法的封裝

#方法的封裝一class Myclass def public_method end PRivate def private_method end protected def protected_method endend#方法的封裝一class Myclass def public_method end def private_method end def protected_method end public :public_method public :private_method public :protected_methodend

多功能型(Duck type)

class Duck def quack puts "quack!!" endendclass Mallard def quack puts "quaasdfasck!!" endendbirds = [Duck.new,Mallard.new,Object.new ]birds.each do |duck| duck.quack if duck.respond_to? :quack //檢查是否有quack方法end

code block(一種匿名方法,或叫做closure)

one line

5.times {puts "Ruby rokes"}1.upto(5) { |x| puts x}

more lines

people = ["Divid", "john","Mary"]people.each do |person| puts personend

more code block

#迭代造出另一個陣列(map)a = ['a','b','c','d','e','f']a.map {|x| x + '!'}puts a.inspect #=> ["a!", "b!", "c!", "d!", "e!", "f!"]#找出符合條件的值b = [1,2,3,4]b.find_all{|x| x % 2 ==0}b.inspect #=> [2, 4]#迭代碰到符合條件的刪除c =["a", "b", "c", "d", "e", "f"]c.delete_if{|x| x >= "c"}c.inspect #=> ["a", "b"]#客制化排序d = [2,5,4,6]d.sort!{|a,b| a <=> b}d.inspect #=> [2, 4, 5, 6]計算總和(5..10).reduce {|sum,n | sum+n} # =>45#找出最長字符串longest = ["abc",'abcde','abcd','abcdefe']longest.reduce do |memo,Word| (memo.length > word.length)? memo :wordend # =>'abcdefe' #執行一次呼叫pre file = File.new("testfile",'r') 處理內容 file.close ruby習慣寫法 File.open("testfile",'r') do |file| 處理內容 end #自動關閉文檔

Yield

1.在方法中使用yield來執行code block #定義方法 def call_block puts "start" yield yield puts "end" end call_block{puts "Block is cool"} #輸出如下: start Block is cool Block is cool end2.帶參數的code block def call_block yield(1) yield(2) yield(3) end call_block{|i| puts "#{i} Block is cool"} #輸出如下: 1 Block is cool 2 Block is cool 3 Block is cool

Proc Object

def call_block(&block) block.call(1) block.call(2) block.call(3)endcall_block{|i| puts "#{i} Block is cool"}||先宣告一個Proc對象proc1 = Proc.new{|i| puts "#{i}: Block is cool"}proc2 = lambda{|i| puts "#{i}: Block is cool"}#輸出如下 1 Block is cool 2 Block is cool 3 Block is cool

傳遞不定參數的方法

def my_sum(*val) #val是個陣列 val.inject(0){|sum,v| sum+v}endmy_sum(1,2,3,4,5)# 輸出 15

參數尾數Hash,可省略{}

def my_print(a,b,options) puts a puts b puts options[:x] puts options[:y] puts options[:z]endmy_print("A","B",{x:1,y:2,z:3})my_print("A","B",x:1,y:2,z:3)#結果相同
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 海盐县| 宿迁市| 普定县| 左权县| 建水县| 龙海市| 天柱县| 图木舒克市| 九台市| 潍坊市| 思南县| 佛山市| 凤翔县| 阿图什市| 湖北省| 灵璧县| 临漳县| 施秉县| 分宜县| 九寨沟县| 兴和县| 南雄市| 临夏市| 龙泉市| 新田县| 都江堰市| 马公市| 峡江县| 绵阳市| 康乐县| 普格县| 定南县| 定陶县| 遂昌县| 陕西省| 清原| 武邑县| 稷山县| 石河子市| 抚松县| 泗洪县|