首页>itarticle>ruby – basic data structures, array, list, and hash
ruby – basic data structures, array, list, and hash
admin11月 12, 20200
Arrays
Array indexing starts at 0, as in C or Java. A negative index is assumed relative to the end of the array — that is, an index of -1 indicates the last element of the array, -2 is the next to last element in the array, and so on.
nums = Array.new(10) {|e| e = e * 2} puts "#{nums}"# 024681012141618
nums = Array.new(10) {|e| e = e + 1} puts "#{nums}"# 12345678910
#----------------
nums = Array.[](1,2,3,4,5) puts "#{nums}"# 12345
nums = Array[1,2,3,4,5] puts "#{nums}"# 12345
The Kernel module available in core Ruby has an Array method, which only accepts a single argument. Here, the method takes a range as an argument to create an array of digits:
1 2
digits = Array(0..3) puts "#{digits}"# 0123
Array built-in methods
Following is the way to create an instance of Array object:
1 2 3 4
Array.[](...) Array[...] [...] Array(...)
List
1
%w(foo bar)
is a shortcut for
1
["foo", "bar"].
%w quotes like single quotes '' (no variable interpolation, fewer escape sequences), while %W quotes like double quotes "".
A Hash is a collection of key-value pairs like this: "employee" => "salary". It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index.
The order in which you traverse a hash by either key or value may seem arbitrary and will generally not be in the insertion order. If you attempt to access a hash with a key that does not exist, the method will return nil.
Creating Hashes
Create an empty hash with the new class method:
1
months = Hash.new
You can also use new to create a hash with a default value, which is otherwise just nil:
近期评论