Yulia
Yulia

Reputation: 1585

Make an array in Ruby

I am very beginner in Ruby and probably the question is too easy but well, I've already spent some time on it and couldn't find a solution. My Ruby script takes a number (ex 10) and a name (ex Vincent). What I want is to make an array looking like

Vincent0
Vincent1.. 
Vincent9

I can't figure a way to make it..

Upvotes: 1

Views: 500

Answers (5)

krohrbaugh
krohrbaugh

Reputation: 1320

Using Array.new with a block (docs):

def create_array(count, name)
  Array.new(10) { |i| "#{name}#{i} }
end

Using Enumerable#reduce (docs):

def create_array(count, name)
  (0...count).reduce([]) { |m,i| m << "#{name}#{i}" }
end

Or using Enumerable#each_with_object (docs):

def create_array(count, name)
  (0...count).each_with_object([]) { |i,a| a << "#{name}#{i}" }
end

Using it:

# Using the array (assigning to variables)
array = create_array(10, 'Vincent') # => ['Vincent0', 'Vincent1', 'Vincent2' ...]
name  = array[1]                    # => 'Vincent1'

Upvotes: 3

sparkymat
sparkymat

Reputation: 10028

def arrayfy(string, number)
  arr = []
  0.upto(number-1) do |i|
    arr << "#{string}#{i}"
  end
  return arr
end

Update: To add these as variables to the class

class Foo
  def arrayfy(string, number)
    0.upto(number-1) do |i|
      var_string = "@#{string}#{i}"
      var_symbol = var_string.to_sym
      self.instance_variable_set(var_symbol, "")
    end
  end
end

Upvotes: 6

Andrew Grimm
Andrew Grimm

Reputation: 81651

Array.new(10) {|i| "Vincent#{i}"}

gives you

["Vincent0", "Vincent1", "Vincent2", "Vincent3", "Vincent4", "Vincent5", 
"Vincent6", "Vincent7", "Vincent8", "Vincent9"]

The documentation for Array is available at http://www.ruby-doc.org/core/classes/Array.html (googling for Array RDoc will give you the URL).

The bit in the braces ({|i| "Vincent#{i}"}) is called a block. You'll definitely want to learn about them.

Upvotes: 3

Michael Kohl
Michael Kohl

Reputation: 66867

Just for the record, a solution in a more functional style:

>> def arrayify(str, n)
..   ([str] * n).zip(0...n).map(&:join)
..   end 
#=> nil
>> arrayify('Vincent', 10) 
#=> ["Vincent0", "Vincent1", "Vincent2", "Vincent3", "Vincent4", "Vincent5", "Vincent6", "Vincent7", "Vincent8", "Vincent9"]

Upvotes: 1

bor1s
bor1s

Reputation: 4113

def array_maker(number, string)
  result = []
  for i in 0..number do
    result << "#{string}#{i}"
  end
  result
end

Upvotes: 0

Related Questions