Last active
August 29, 2015 14:26
-
-
Save yoavlt/e2fbd06db3081df5e8e1 to your computer and use it in GitHub Desktop.
ネストしたデータ構造を操作するput_inとupdate_inが便利 ref: http://qiita.com/yoavlt/items/b973210605d6f771b9d1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
iex> foo = %{person: %{name: "foo", age: 21}, place: "Shibuya"} | |
iex> put_in(foo.person.age, 30) | |
%{person: %{age: 30, name: "foo"}, place: "Shibuya"} | |
iex> foo | |
%{person: %{age: 21, name: "foo"}, place: "Shibuya"} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
iex> foo = %{person: %{name: "foo", age: 21}, place: "Shibuya"} | |
iex> update_in(foo.person.age, fn age -> age + 1 end) | |
%{person: %{age: 22, name: "foo"}, place: "Shibuya"} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule User do | |
defstruct name: nil, text: nil, place: nil | |
end | |
defmodule Message do | |
defstruct user: nil, text: nil, place: nil | |
end | |
message = %Message{user: %User{name: "foo", age: 21}, text "Yay!", place: "Shibuya"} | |
update_in(message.user.age, &(&1 + 1)) | |
// => %Message{place: "Shibuya", text: "Yay!", user: %User{age: 22, name: "foo"}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment