ruby入门_哈希表

就是一个键值对对象

# define
person={
  "name" => "Tom",
  "age" => "20",
  "sex" => "male",
  1 => 1,
  2 => "abc"
}

# get value
puts "name = #{person["name"]}"
puts "age = #{person["age"]}"
puts "sex = #{person["sex"]}"
puts "1 = #{person[1]}"
puts "2 = #{person[2]}"

# common methods
# size = length
# include? = has_key?
puts "size = #{person.size}"
puts "length = #{person.length}"
puts "include?('name') = #{person.include?('name')}"
puts "include?('error') = #{person.include?('error')}"
puts "has_key?('name') = #{person.has_key?('name')}"
puts "has_key?('error') = #{person.has_key?('error')}"

person.delete(1)
person.delete(2)

puts "keys = #{person.keys}"
puts "values = #{person.values}"

# iterate methods
# each = each_pair
person.each do |key,value|
  puts "    key = #{key},value = #{value}"
end

puts

person.each_key do |key|
  puts "    key = #{key}"
end

puts

person.each_value do |value|
  puts "    value = #{value}"
end

puts

person.each_pair do |key,value|
  puts "    key = #{key},value = #{value}"
end

输出

name = Tom
age = 20
sex = male
1 = 1
2 = abc
size = 5
length = 5
include?('name') = true
include?('error') = false
has_key?('name') = true
has_key?('error') = false
keys = ["name", "age", "sex"]
values = ["Tom", "20", "male"]
    key = name,value = Tom
    key = age,value = 20
    key = sex,value = male


    key = name
    key = age
    key = sex


    value = Tom
    value = 20
    value = male


    key = name,value = Tom
    key = age,value = 20
    key = sex,value = male

你可能感兴趣的:(Ruby,each,pair)