Array & Hash

Array

array1=[1,2,3]
array2=[true,2,"a",[1,2,3,4]]

๋ฐฐ์—ด์—๋Š” ๋‹ค์–‘ํ•œ ํ˜•ํƒœ์˜ ๋ฐ์ดํ„ฐ ํƒ€์ž…(boolean, number, string, array)์„ ๊ฐ™์ด ์“ธ ์ˆ˜ ์žˆ๋‹ค.

- ๋ฐฐ์—ด์˜ ์ ‘๊ทผ๋ฐฉ๋ฒ•

index๋ฅผ ํ†ตํ•ด์„œ ์ ‘๊ทผ ํ•  ์ˆ˜ ์žˆ๋‹ค! ๋ฐฐ์—ด์˜ index๋Š” 0๋ถ€ํ„ฐ ์‹œ์ž‘ํ•ด ๋ฐฐ์—ด์˜ ํฌ๊ธฐ-1 ๊นŒ์ง€๊ฐ€ ๋ฒ”์œ„์ด๋‹ค.

arr=[1,2,3,4,5]

1

2

3

4

5

arr[0]

arr[1]

arr[2]

arr[3]

arr[4]

arr = [1,"a",3,"b",true]
#=> [1, "a", 3, "b", true]
arr
#=> [1, "a", 3, "b", true]
arr[0]
#=> 1
arr[4]
#=> true

Hashes

: a collection of key-value pairs

hash ์ƒ์„ฑ๋ฐฉ๋ฒ•

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

=>hash rocket๋ฅผ ์ด์šฉํ•ด์„œ key๋ฅผ ์ง€์ •ํ•ด์ค€๋‹ค.

my_hash = Hash.new
my_hash["key"] = "value"

# Hash๋Š” ๋ฐ˜๋“œ์‹œ H๊ฐ€ ๋Œ€๋ฌธ์ž์—ฌ์•ผํ•œ๋‹ค.

# default value ์ง€์ •
h=Hash.new(โ€œdefault valueโ€)

hash value์— ์ ‘๊ทผํ•˜๋Š” ๋ฐฉ๋ฒ•

hash = "key"

Symbol(:)

"string" == :string # false

  • arenโ€™t strings

  • thereโ€™s only one copy of any particular symbol at a given time

  • ์ฃผ๋กœ hash์˜ ํ‚ค๋กœ ๋งŽ์ด ์‚ฌ์šฉ๋œ๋‹ค.

    sounds = {
    :cat => "meow",
    :dog => "woof",
    :computer => 10010110,
    }
  • ๋งŒ๋“ค์–ด์ง€๋ฉด ๋ฐ”๊ฟ€ ์ˆ˜ ์—†๋‹ค.

  • Only one copy of any symbol exists at a given time, so they save memory;

  • Symbol-as-keys are faster than strings-as-keys because of the above two reasons.

hash rocket(=>)์—์„œ ๋ฌธ๋ฒ•์ด ๋ฐ”๋€œ

new_hash = {
  key1: value1,
  key2: value2,
  key3: value3
}

Last updated