Skip to content

Instantly share code, notes, and snippets.

@yoavlt
Last active August 29, 2015 14:26
Show Gist options
  • Save yoavlt/e2fbd06db3081df5e8e1 to your computer and use it in GitHub Desktop.
Save yoavlt/e2fbd06db3081df5e8e1 to your computer and use it in GitHub Desktop.
ネストしたデータ構造を操作するput_inとupdate_inが便利 ref: http://qiita.com/yoavlt/items/b973210605d6f771b9d1
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"}
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"}
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