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]
Create array in Ruby with begin value, end value and step for float values
For floats with custom stepping you can use Numeric#step like so:
-1.25.step(by: 0.5, to: 1.25).to_a
# => [-1.25, -0.75, -0.25, 0.25, 0.75, 1.25]
If you are looking on how to do this with integer values only, see this post or that post on how to create ranges and simply call .to_a
at the end. Example:
(-1..1).step(0.5).to_a
# => [-1.0, -0.5, 0.0, 0.5, 1.0]
How to initialize all the values of a two dimensional array using Ruby, is there any way to do it in 1 step?
Sure
Array.new(3) { Array.new(4, 0) }
=> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
How to create array from 1 to n digit with single line of code in ruby
Convert a range into an array.
(1..n).to_a
Fill array with element N times
For immutable objects like Fixnums etc
Array.new(5, 1234) # Assigns the given instance to each item
# => [1234, 1234, 1234, 1234, 1234]
For Mutable objects like String Arrays
Array.new(5) { "Lorem" } # Calls block for each item
# => ["Lorem", "Lorem", "Lorem", "Lorem", "Lorem"]
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]
Printing an array of arrays on one line in console (one line per master array object) in Ruby
your_array.each do |person|
puts person.join(" ")
end
Why is it not possible to fill an array using an each do loop in Ruby?
Solution
You need :
array = Array.new(4) do |i|
5
# or some logic depending on i (the index between 0 and 3)
end
Your code
array = Array.new(4)
array is now an Array with 4 elements (nil
each time).
array.each
iterates over those 4 elements (still nil
), and sets i
as block-local variable equal to nil
.
Inside this block, you override i
with 5, but you don't do anything with it. During the next iteration, i
is set back to nil
, and to 5
, and so on...
You don't change the original array, you only change local variables that have been set equal to the array elements.
how to work with Array without changing its initial values?
Your code has the same problems as this would in Python:
edges = [[[1, 2], [100, 200]], [[700, 400], [1000, 2000]]]
new_edges = list(edges)
for edge in edges:
for point in edge:
point.insert(0, 808912)
print(edges)
I.e. you transform the outer array, but the inner arrays are only held by reference, and thus changing one (by insert
) is changing the deep content of both edges
and new_edges
. These kinds of problems are very easily understood by stepping through your code with this tool (despite the name, it works for both Python and Ruby).
In Ruby, instead of using insert
, which modifies an array, you can use +
, which does not:
edges = [[[1, 2], [100, 200]], [[700, 400], [1000, 2000]]]
new_edges = edges.map { |edge| edge.map { |point| [808912] + point } }
# => [[[808912, 1, 2], [808912, 100, 200]], [[808912, 700, 400], [808912, 1000, 2000]]]
edges
# => [[[1, 2], [100, 200]], [[700, 400], [1000, 2000]]]
Intitalizing Object with Array of objects from another class Ruby
Your problem is assigning a new value to @stars_array
variable on each iteration. There are multiple ways to deal with it:
@stars_array = (0..99).map { |i| Star.new('unknown_star',i) }
By the way, there is a couple of design issues (just for your attention):
Why variable is called
stars_array
, not juststars
?Why would ever instance of
Star
class have some object named@star
inside? Recursion? :) Seems like@name
would be proper and more clear attribute's name.Don't miss indentation.
EDIT: About DB-mapping. Most common way - inherit both classes from ActiveRecord::Base, and create one-to-many relation from solar system to stars. Each class will have it's own table. Takes absolutely no efforts.
Related Topics
My Classes Can't Use Shoes Methods Like Para
Check If String Is Repetition of an Unknown Substring
Ruby Was-Sdk V2:Seahorse::Client::Networkingerror Exception: Ssl_Connect
Create and Initialize Instances of a Class with Sequential Names
Differencebetween Def Func(Var) and Def Func=(Var)
Can Ruby Tell If It Is Called from an Interactive Shell or Cron
How to Display Error Messages in a Multi-Model Form with Transaction
How to Display a Link to Individual Microposts? (Ruby on Rails 3)
Assets Precompiling Error with Jquery UI Plugin
How to Sign Out in a Rails App, Using Devise Gem, No Route Matches /Users/Sign_Out
How to Extract Specific Elements from an Array
Delayedjob: "Job Failed to Load: Uninitialized Constant Syck::Syck"
With Nokogiri I am Getting Error "Initialize': Getaddrinfo: No Such Host Is Known. (Socketerror)"
How to Output My Ruby Commandline Text in Different Colours
How to Share Image and Description Using Social_Share_Button in Rails