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