I'm trying to extract values from list of tuples:
s3_headers = %{headers: [{"x-amz-id-2","yQKurzVIApkxxxxxxxxxxxxxxxxxxxxxxxxxxxxxFBINsPxe+7Vc="},
{"x-amz-request-id", "82xxxxxxxxx23"},
{"Date", "Thu, 25 May 2017 22:03:09 GMT"},
{"Last-Modified", "Thu, 25 May 2017 21:42:28 GMT"},
{"ETag", "\"6f04733333333333333368997\""},
{"x-amz-meta-original_name", "Screenshot from 2016-11-27 17-32-03.png"},
{"Accept-Ranges", "bytes"}, {"Content-Type", ""},
{"Content-Length", "612391"}, {"Server", "AmazonS3"}], status_code: 200}
The way how I manage to do it so far is like this:
{"x-amz-meta-original_name", original_name } = s3_headers |> List.keyfind("x-amz-meta-original_name", 0)
{"Content-Length", content_length } = s3_headers |> List.keyfind("Content-Length", 0)
{"Content-Type", content_length } = s3_headers |> List.keyfind("Content-Type", 0)
It feels like overcomplication can you recommend better way ?
Elixir tuples are stored contiguously in memory and are accessed by index. A tuple literal uses a pair of curly braces {} . The elem/2 function is used to access a data item in a tuple. The length of a tuple can be found with the tuple_size/1 function.
In Elixir and Erlang we use `list ++ [elem]` to append elements.
Lists are a basic data type in Elixir for holding a collection of values. Lists are immutable, meaning they cannot be modified. Any operation that changes a list returns a new list. Lists implement the Enumerable protocol, which allows the use of Enum and Stream module functions.
I usually convert tuple lists with string keys to a Map. Then you access with string keys. This will take a little more time upfront, but much less time of each access than Enum.find
iex(19)> headers = Enum.into s3_headers[:headers], %{}
%{"Accept-Ranges" => "bytes", "Content-Length" => "612391",
"Content-Type" => "", "Date" => "Thu, 25 May 2017 22:03:09 GMT",
"ETag" => "\"6f04733333333333333368997\"",
"Last-Modified" => "Thu, 25 May 2017 21:42:28 GMT", "Server" => "AmazonS3",
"x-amz-id-2" => "yQKurzVIApkxxxxxxxxxxxxxxxxxxxxxxxxxxxxxFBINsPxe+7Vc=",
"x-amz-meta-original_name" => "Screenshot from 2016-11-27 17-32-03.png",
"x-amz-request-id" => "82xxxxxxxxx23"}
iex(20)> original_name = headers["x-amz-meta-original_name"]
"Screenshot from 2016-11-27 17-32-03.png"
iex(21)> content_length = headers["Content-Length"]
"612391"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With