Skip to content

Instantly share code, notes, and snippets.

@fokayx
Last active August 29, 2015 14:18
Show Gist options
  • Save fokayx/9f542da4b19f0d48d70a to your computer and use it in GitHub Desktop.
Save fokayx/9f542da4b19f0d48d70a to your computer and use it in GitHub Desktop.
Method: map, map!_RubyNerd
  • map { |item| block } → new_ary

  • map → Enumerator

把Array中每一個元件一一丟入所定義的block中執行後,回傳一個值來自於block的新array。如果沒有定義block,則回傳Enumerator。

a = ["a", "b", "c", "d"]
=> ["a", "b", "c", "d"]

a.map { |x| x + "!" }
=> ["a!", "b!", "c!", "d!"]

a.map.with_index { |x, i| x * i }
=> [" ", "b", "cc", "ddd"]

a
=> ["a", "b", "c", "d"]

a.map
=> <Enumerator: ["a", "b", "c", "d"]:map>

  • map! {|item| block } → ary

  • map! → Enumerator

map!:一樣是把Array中的每個元素傳入定義的block執行後,回傳一個值來自於block的新array,但是會重新定義原本的Array。

a = ["a", "b", "c", "d"]
=> ["a", "b", "c", "d"]

a.map!{|x| x + "!"}
=> ["a!", "b!", "c!", "d!"]

a
=> ["a!", "b!", "c!", "d!"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment