MARK CHANG'S BLOG

若發生公式跑掉或無法正常顯示的情形,請在公式上按右鍵設定:math setting-> math render->SVG
  • About Me
  • Archive
  • feeds

Posts match “ ruby ” tag:

almost 9 years ago

Ruby -- struct v.s openStruct

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!"
Read on →
  • ruby
  • March 12, 2014 23:26
  • Permalink
  • Comments
 
over 8 years ago

Ruby -- Enumerable 1 : Collect , Inject

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 →
  • ruby
  • enumerable
  • map
  • reduce
  • functional_programming
  • April 30, 2014 23:06
  • Permalink
  • Comments
 

Copyright © 2013 cpmarkchang . Powered by Logdown.
Based on work at subtlepatterns.com.