Ruby on Rails tutorial – 4.6 Exercises

Aktualizováno: 23. 9. 2020, datum vydání: 17. 2. 2015

Uvádím zde řešení cvičení k tutoriálu Ruby on Rails od Michaela Hartla – kapitola 4.6.

Úloha 1 (Listing 4.14)

>> def string_shuffle(s)
>>   s.split('').shuffle.join
>> end
=> :string_shuffle
>> string_shuffle("foobar")
=> "boofra"

Úloha 2 (Listing 4.15)

?> class String
>>   def shuffle
>>     self.split('').shuffle.join
>>   end
>> end
=> :shuffle
>> "foobar".shuffle
=> "rabfoo"

Úloha 3

Vytvoření hashe person:

>> person1 = { first: "Petr", last: "Novak" }                                                                                                
=> {:first=>"Petr", :last=>"Novak"}
>> person2 = { first: "Alena", last: "Bila" }                                                                                                    
=> {:first=>"Alena", :last=>"Bila"}
>> person3 = { first: "Zdenek", last: "Holohlavy" }                                                                                              
=> {:first=>"Zdenek", :last=>"Holohlavy"}

Naplnění hashe params:

>> params = { father: person1, mother: person2, child: person3 }
=> {:father=>{:first=>"Petr", :last=>"Novak"}, :mother=>{:first=>"Alena", :last=>"Bila"}, :child=>{:first=>"Zdenek", :last=>"Holohlavy"}}
>> params[:father][:first] 
=> "Petr"

Úloha 4 Merge

>> { "a" => 100, "b" => 200 }.merge({ "b" => 300 })
=> {"a"=>100, "b"=>300}

Zde je API dokumentace k metodě Merge. Dojde ke sloučení dvou hashů s tím, že duplikátní údaje jsou nahrazeny druhým hashem.

Další články