Writing a conditional loop using the Faker gem in ruby

Viewed 218

I'm trying to write a loop that would return 25 unique first names from the Faker gem in ruby, with the condition that each name is >= 5 characters.

I've managed to create the loop that returns the 25 unique names, but have been unable to correctly produce name.length condition. I've tried the following attempts:

Attempt 1:

names = [Faker::Name.unique.first_name]
names.each do |name|
  puts name if first_name.length >= 5
  25.times do 
    puts "#{Faker::Name.unique.first_name}"
  end
end

Attempt 2:

names = [Faker::Name.unique.first_name]
  25.times do 
    puts "#{Faker::Name.unique.first_name}"
  names.each do |name|
    puts name if name.length >= 5
    end
end

What am I doing incorrectly?

2 Answers

names = [Faker::Name.unique.first_name] create one element in array, so to fix that you should create names that much your condition and then you can display them.

# generate names
names = []
while names.size <= 25 do 
  name = Faker::Name.unique.first_name
  names << name if name.length >= 5
end

# display names
names.each do |name| 
  puts name 
end

You can do something like this:

require 'faker'

names = []
until names.length == 25 do
  name = Faker::Name.unique.first_name
  names << name if name.length >= 5
end
puts names
Related