Notice
Recent Posts
Recent Comments
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Tags
more
Archives
Today
Total
관리 메뉴

INSPECT

[Ruby]3. Hash 본문

Ruby on Rails - 멋쟁이 사자처럼

[Ruby]3. Hash

INSPECT 2017. 1. 26. 14:55
Introduction to Hashes

We know that arrays are indexed with numbers that start with 0 and go up to the array's length minus one. (Think about it: an array with four elements has the indices 0, 1, 2, and 3.)

But what if we want to use numeric indices that don't go in order from 0 to the end of the array? What if we don't want to use numbers as indices at all? We'll need a new array structure called a hash.

Hashes are sort of like JavaScript objects or Python dictionaries. If you haven't studied those languages, all you need to know that a hash is a collection of key-value pairs. Hash syntax looks like this:

hash = {
  key1 => value1,
  key2 => value2,
  key3 => value3
}

Values are assigned to keys using =>. You can use any Ruby object for a key or value.

Adding to a Hash

We can add to a hash two ways: if we created it using literal notation, we can simply add a new key-value pair directly between the curly braces. If we used Hash.new, we can add to the hash using bracket notation:

pets = Hash.new
pets["Stevie"] = "cat"
# Adds the key "Stevie" with the
# value "cat" to the hash
Accessing Hash Values

You can access values in a hash just like an array.

pets = {
  "Stevie" => "cat",
  "Bowser" => "hamster",
  "Kevin Sorbo" => "fish"
}

puts pets["Stevie"]
# will print "cat"
  1. In the example above, we create a hash called pets.
  2. Then we print cat by accessing the key "Stevie" in the `pets hash.

참고 : codecademy.com

'Ruby on Rails - 멋쟁이 사자처럼' 카테고리의 다른 글

[Ruby] 4. Symbol  (0) 2017.01.28
[Ruby]2  (0) 2017.01.26
[Ruby] 1  (0) 2017.01.26
[CSS] 웹 폰트 사용하기  (0) 2017.01.20
[C9] css: command not found 오류  (0) 2017.01.20
Comments