国产探花免费观看_亚洲丰满少妇自慰呻吟_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)#結果相同
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 津南区| 罗平县| 盘山县| 汝州市| 郸城县| 虹口区| 新余市| 泌阳县| 宁乡县| 嘉峪关市| 许昌市| 嘉荫县| 嘉兴市| 慈溪市| 郯城县| 青阳县| 铅山县| 江西省| 馆陶县| 历史| 东兰县| 桐庐县| 江达县| 湛江市| 西贡区| 文成县| 长岛县| 宜阳县| 广东省| 绿春县| 托克逊县| 胶州市| 胶南市| 进贤县| 清新县| 福建省| 称多县| 合川市| 新邵县| 阿荣旗| 资阳市|