Skip to content

Commit eef58c3

Browse files
committed
added extension exercise summary
1 parent 9defa63 commit eef58c3

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
---
2+
title: (Ext) Exercise summary
3+
---
4+
It's easy to convert a `hash` into an `array`.
5+
{% highlight ruby %}
6+
h = {'a'=>1, 'b'=>2, 'c'=>3}
7+
8+
a = h.to_a
9+
# => [["a", 1], ["b", 2], ["c", 3]]
10+
{% endhighlight %}
11+
To convert back from an `array` to a `hash`, use
12+
{% highlight ruby %}
13+
h=Hash[a]
14+
# => {"a"=>1, "b"=>2, "c"=>3}
15+
{% endhighlight %}
16+
17+
You can unpack a `hash` into its keys and values with the `.keys` and `.values` methods
18+
19+
{% highlight ruby %}
20+
h = {'one'=>1, 'two'=>2, 'three'=>3}
21+
22+
keys = h.keys
23+
#=> ["one", "two", "three"]
24+
values = h.values
25+
#=> [1, 2, 3]
26+
27+
28+
{% endhighlight %}
29+
30+
and put it back together with
31+
32+
{% highlight ruby %}
33+
h = Hash[keys.zip(values)]
34+
35+
# => {"one"=>1, "two"=>2, "three"=>3}
36+
{% endhighlight %}
37+

0 commit comments

Comments
 (0)