almost 9 years ago
1.Struct
在 Ruby 程式語言裡面, 如果想要定義一個新的類別, 但又覺得重新寫一個 class 太麻煩,
有比較方便的方法,
irb> Customer = Struct.new(:name, :phone) do
irb> def say_hello
irb> "Hello, I'm #{name}!"
irb> end
irb> end
=> Customer
irb> Gary = Customer.new("Gary", "0923-355-599")
=> #<struct Customer name="Gary", phone="0923-355-599">
irb> Gary.phone
=> "0923-355-599"
irb> Gary.say_hello
=> "Hello, I'm Gary!"
over 8 years ago
Introduction
在 ruby 裡面, 也有類似 functional programming style 的東西, 像是 map , reduce 之類的
但是這些不是像 python 那樣是屬於 build in function , 像這樣
>>> map(lambda x:x*2 ,[1,2,3,4])
[2, 4, 6, 8]
在 ruby 裡面的 map 是這樣, 如下
irb(main):001:0> [1,2,3,4].map{|x| x*2}
=> [2, 4, 6, 8]
它是 Enumerable Type 的 Method
除此之外, map 和 reduce 在 ruby 裡面還有其他的別名, 就是 collect 和 inject
Read on →