|
7 | 7 | load: prev |
8 | 8 | --- |
9 | 9 |
|
10 | | -Okay we now have a list of plays from the internet. The list was in the json format. |
11 | | -Fortunately for us Ruby kindly provides a method to convert json data to a Ruby hash. |
12 | | -The _get\_shakey_ method already did that for us. |
13 | | - |
14 | | -But since the structure of the json data is retained in the hash, it is still a bit difficult to read. |
15 | | -Let us write a method to display the plays nicely. |
16 | | - |
17 | | -If you inspect the list of plays carefully you will see that it has a kind of nested |
18 | | -structure. (This is actually quite common in data you get from the internet.) |
19 | | -Looks like this: |
20 | | - |
21 | | -<ul> |
22 | | - <li>"William Shakespeare" |
23 | | - <ul> |
24 | | - <li>"1" |
25 | | - <ul> |
26 | | - <li>"title": "The Two Gentlemen of Verona"</li> |
27 | | - <li>"finished": 1591</li> |
28 | | - </ul> |
29 | | - </li> |
30 | | - <li>"2" |
31 | | - <ul> |
32 | | - <li>"title": "The Taming of the Shrew"</li> |
33 | | - <li>"finished": 1591</li> |
34 | | - </ul> |
35 | | - </li> |
36 | | - <li>...</li> |
37 | | - </ul> |
38 | | - </li> |
39 | | -</ul> |
40 | | - |
41 | | -To list the plays we first have to access the top "William Shakespeare" hash element by its name. |
42 | | -Next we have to __iterate__ through each element below it. |
43 | | - |
44 | | -Ruby has a method for iterating. It is called __each__. We have seen it before when |
45 | | -creating our book rating system. |
46 | | - |
47 | | -Everything that method __each__ returns is passed to a block: |
48 | | - |
49 | | - s = get_shakey |
50 | | - |
51 | | - s["William Shakespeare"].each { |key, val| |
52 | | - puts val["title"] |
53 | | - } |
54 | | - |
55 | | - |
56 | 10 | Bien, maintenant nous avons une liste de pièces de théâtre provenant d'Internet. La liste est au format json. |
57 | 11 | Heureusement pour nous, Ruby fournit gentiment une méthode pour convertir les données json en un hash Ruby. |
58 | 12 | La méthode _get\_shakey_ l'a déjà fait pour nous. |
@@ -96,4 +50,4 @@ Tout ce que la méthode __each__ retourne est passé à un bloc : |
96 | 50 |
|
97 | 51 | s["William Shakespeare"].each { |key, val| |
98 | 52 | puts val["title"] |
99 | | - } |
| 53 | + } |
0 commit comments