Element Assignment — Sets the element at index
, or replaces a subarray from the start
index for length
elements, or replaces a subarray specified by the range
of indices.
If indices are greater than the current capacity of the array, the array grows automatically. Elements are inserted into the array at start
if length
is zero.
Negative indices will count backward from the end of the array. For start
and range
cases the starting index is just before an element.
An IndexError
is raised if a negative index points past the beginning of the array.
See also Array#push
, and Array#unshift
.
a = Array.new a[4] = "4"; #=> [nil, nil, nil, nil, "4"] a[0, 3] = [ 'a', 'b', 'c' ] #=> ["a", "b", "c", nil, "4"] a[1..2] = [ 1, 2 ] #=> ["a", 1, 2, nil, "4"] a[0, 2] = "?" #=> ["?", 2, nil, "4"] a[0..2] = "A" #=> ["A", "4"] a[-1] = "Z" #=> ["A", "Z"] a[1..-1] = nil #=> ["A", nil] a[1..-1] = [] #=> ["A"] a[0, 0] = [ 1, 2 ] #=> [1, 2, "A"] a[3, 0] = "B" #=> [1, 2, "A", "B"]
Stores the specified string value in the database, indexed via the string key provided.
Attribute Assignment—Sets the value of the given struct member
or the member at the given index
. Raises NameError
if the member
does not exist and IndexError
if the index
is out of range.
Customer = Struct.new(:name, :address, :zip) joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345) joe["name"] = "Luke" joe[:zip] = "90210" joe.name #=> "Luke" joe.zip #=> "90210"
Associates the value value with the specified key.
Sets the value of an attribute.
require "ostruct" person = OpenStruct.new("name" => "John Smith", "age" => 70) person[:age] = 42 # equivalent to person.age = 42 person.age # => 42