A rough note about Ruby arrays and hash objects

A note about Ruby arrays and hash objects. Since I know the basics of arrays, I would like to make a note of how to write them unique to ruby.

When adding elements to an array

num = ["one"]
num << "two"
p num  # ["one", "two"]

Key and value definitions using hashes

numKey = { one: 1, two: 2 }
p numKey  # {:one=>1, :two=>2}
p numKey[:two]  # 2

Array definition in% notation

# numbers = ["one", "two", "three"]Same meaning
numbers = %W( one two three )
p numbers  # ["one", "two", "three"]

Extract the elements in the array one by one

%w[one two three].each do |num|
    p num
end
# "one"
# "two"
# "three"

Adds a value to the original array and returns a new array.

nums = %w[one two three four].map{ |num| "Numbers: #{num}" }
p nums  # ["Numbers: one", "Numbers: two", "Numbers: three", "Numbers: four"]

Recommended Posts

A rough note about Ruby arrays and hash objects
[Swift] A note about function and closure
About Ruby arrays
A note about the Rails and Vue process
A note about Java GC
A note about the scope
About Ruby hashes and symbols
A private note about AtomicReference
About Ruby and object model
About Ruby classes and instances
A note about the seed function of Ruby on Rails
About the behavior of ruby Hash # ==
A note about RocksDB's Column Families
[Ruby] Difference between symbol variables and character string variables. About the difference between [: a] and ['a'].
About Ruby single quotes and double quotes
About Ruby product operator (&) and sum operator (|)
About object-oriented inheritance and about yield Ruby
Note: Difference between Ruby "p" and "puts"
Explanation of Ruby Time and Date objects
Comparison of JavaScript objects and Ruby classes
[Ruby] A program that uses search and each_with_index
[Understanding] Differences between hashes and arrays in Ruby
A story about a very useful Ruby Struct class
A story about Apache Wicket and atomic design
[ruby] How to assign a value to a hash by referring to the value and key of another hash