Can I create an array in Ruby with default values?
Given that Ruby returns nil
for a non-existing element (as opposed to index-out-of-bounds type error), you could just use an "or":
a = [1,2,3]
puts a[5] # => nil
puts a[5] || "a default" # => a default
You could take the monkey patch approach, but you probably would not want to do this in anything larger than a 1-file script:
a = [1,2,3]
def a.[](index)
self.at(index) || "a default"
end
puts a[5] # => "a default"
Creating a Hash with values as arrays and default value as empty array
Lakshmi is right. When you created the Hash using Hash.new([])
, you created one array object.
Hence, the same array is returned for every missing key in the Hash.
That is why, if the shared array is edited, the change is reflected across all the missing keys.
Using:
Hash.new { |h, k| h[k] = [] }
Creates and assigns a new array for each missing key in the Hash, so that it is a unique object.
Create an array with a fixed size, and fill default content with another array?
def fixed_array(size, other)
Array.new(size) { |i| other[i] }
end
fixed_array(5, [1, 2, 3])
# => [1, 2, 3, nil, nil]
How do I assign default values for two-dimensional array?
Just supply a second argument with the value:
array = Array.new(10) { Array.new(10, 4) }
Here, the default value is 4
and thus, a 10*10 2D array is created with default value of 4
.
How to initialize an array in one step using Ruby?
You can use an array literal:
array = [ '1', '2', '3' ]
You can also use a range:
array = ('1'..'3').to_a # parentheses are required
# or
array = *('1'..'3') # parentheses not required, but included for clarity
For arrays of whitespace-delimited strings, you can use Percent String syntax:
array = %w[ 1 2 3 ]
You can also pass a block to Array.new
to determine what the value for each entry will be:
array = Array.new(3) { |i| (i+1).to_s }
Finally, although it doesn't produce the same array of three strings as the other answers above, note also that you can use enumerators in Ruby 1.8.7+ to create arrays; for example:
array = 1.step(17,3).to_a
#=> [1, 4, 7, 10, 13, 16]
Populate hash with array keys and default value
Do as below :
def solution(keys,default_val)
Hash[keys.product([default_val])]
end
solution([:key1,:key2],12) # => {:key1=>12, :key2=>12}
Read Array#product
and Kernel#Hash
.
Can't use an array as default values for Ruby Hash?
Try the following instead:
hash = Hash.new{|h, k| h[k] = []}
hash['a'] << 1 # => [1]
hash['b'] << 2 # => [2]
The reason you got your unexpected results is that you specified an empty array as default value, but the same array is used; no copy is done. The right way is to initialize the value with a new empty array, as in my code.
Related Topics
How Does Defining [Square Bracket] Method in Ruby Work
Retrieving a Braintree Customer's Subscriptions
How to Determine the Md5 Digest of a Given Asset in the Rails Asset Pipeline
Devise: How to Override Devise Error Messages on Password Change
Rendering a Partial from a Controller in Rails
Factorygirl Association Model Trouble: "Systemstackerror: Stack Level Too Deep"
Why Is Ruby Unable to Verify an Ssl Certificate
What Command Opens Ruby's Repl
How to Use the Rails Helper "Distance_Of_Time_In_Words" in Plain Old Ruby (Non-Rails)
How to Compare a String Against Multiple Other Strings
Why Doesn't Rails' "Errors.Full_Messages" Replace Attribute and Message Variables
Rails: Plus Sign in Get-Request Replaced by Space
Why Is 'Return a or B' a Void Value Expression Error in Ruby
Could Not Find 'Cocoapods' (>= 0) Among N Total Gem(S) (Gem::Loaderror)
Convert an Array of Integers into an Array of Strings in Ruby