[ create a new paste ] login | about

Link: http://codepad.org/diyELnno    [ raw code | output | fork | 1 comment ]

joshua_cheek - Ruby, pasted on Oct 26:
#Learning Ruby chapter 7

h = {"a" => 1 , "b" => 2 , 3 => "c" , :x => [1,2,3] , [0,1,2] => [:r,:s,:t]}

puts "pre: h = #{h.inspect}"
puts "1 h.length = #{h.length}"
puts "2 h.empty? = #{h.empty?}"

#keys and values
puts "3 h.has_key?(\"b\") = #{h.has_key?("b")}"
puts "4 h.has_key?(\"z\") = #{h.has_key?("z")}"
puts "5 h.has_value?([1,2,3]) = #{h.has_value?([1,2,3])}"
puts "6 h.has_value?([2,3,4]) = #{h.has_value?([2,3,4])}"
puts "7 h.keys = #{h.keys.inspect}"
puts "8 h.values = #{h.values.inspect}"

#iterating
puts "9:"
h.each{ |key,value| puts key.inspect+"/"+value.inspect }
print "\n10 "
h.each_key{ |key| print key.inspect , " " }
print "\n11 "
h.each_value{ |value| print value.inspect , " " }
puts

#merge
h2 = { 9 => "nine" , 10 => "ten" }
puts "12 h.merge(h2) = #{h.merge(h2).inspect}"

#deleting
h.delete(:x)
puts "13 h.delete(:x) = #{h.inspect}"
h.delete_if{ |key,value| key.class.eql? "".class }
puts "14 h.delete_if{ |key,value| key.class.eql? \"\".class } => #{h.inspect}"

#to whatever
puts "15 h.to_s = #{h.to_s.inspect}"
puts "16 h.to_a = #{h.to_a.inspect}"

#same memory space
a = h
puts "17 a = h,  a.object_id == h.object_id returns #{a.object_id == h.object_id}"

#clear
h.clear
puts "h.clear = #{h.inspect}"


Output:
pre: h = {"a"=>1, "b"=>2, 3=>"c", :x=>[1, 2, 3], [0, 1, 2]=>[:r, :s, :t]}
1 h.length = 5
2 h.empty? = false
3 h.has_key?("b") = true
4 h.has_key?("z") = false
5 h.has_value?([1,2,3]) = true
6 h.has_value?([2,3,4]) = false
7 h.keys = ["a", "b", 3, :x, [0, 1, 2]]
8 h.values = [1, 2, "c", [1, 2, 3], [:r, :s, :t]]
9:
"a"/1
"b"/2
3/"c"
:x/[1, 2, 3]
[0, 1, 2]/[:r, :s, :t]

10 "a" "b" 3 :x [0, 1, 2] 
11 1 2 "c" [1, 2, 3] [:r, :s, :t] 
12 h.merge(h2) = {"a"=>1, "b"=>2, 3=>"c", 9=>"nine", :x=>[1, 2, 3], [0, 1, 2]=>[:r, :s, :t], 10=>"ten"}
13 h.delete(:x) = {"a"=>1, "b"=>2, 3=>"c", [0, 1, 2]=>[:r, :s, :t]}
14 h.delete_if{ |key,value| key.class.eql? "".class } => {3=>"c", [0, 1, 2]=>[:r, :s, :t]}
15 h.to_s = "3c012rst"
16 h.to_a = [[3, "c"], [[0, 1, 2], [:r, :s, :t]]]
17 a = h,  a.object_id == h.object_id returns true
h.clear = {}


Create a new paste based on this one


Comments:
posted by joshua_cheek on Nov 15
My notes from when I read Learning Ruby
(I didn't expect anyone else to look at them, but a friend asked for info on Ruby)
reply