Home > Net >  How to call a method from an another method with ruby?
How to call a method from an another method with ruby?

Time:10-27

I have this little password generating program, I want the method print_password to call the generate_password method, but it just doesn't work

require 'digest'

class Challenge
  KEY = [
    '4', '5', '6', '7',
    '8', '9', 'A', 'B',
    'C', 'D', 'E', 'F',
    '0', '1', '2', '3'
  ]

  def initialize(email)
    @email = email # && raise
    puts 'This object was initialized!'
  end

  def print_password
    puts %(Password 1: {generate_password}) # Here I want to call generate_password method
  end

  private

  def generate_password
    @hash = Digest::SHA1.hexdigest(@email)
    @id = @hash.scan(/\d /).map(&:to_i).inject(: )
    @prng = Random.new(@id)

    prepare_map
    apply_map
  end

  def prepare_map
    @map      = []
    id_string = @id.to_s
    id_size   = id_string.size

    map_string = id_string * (KEY.size.to_f / id_size).ceil

    0.upto(15) do |i|
      @map[i] = map_string[i].to_i
    end

    @map
  end
end

def apply_map
  calculated_key = KEY.shuffle(random: @prng).map.with_index do |char, i|
    (char.bytes[0]   @map[i]).chr
  end

  calculated_key.join
end

 me = Challenge.new('[email protected]') # Initialize new object
 me.print_password # Here I want to print the password

So here at the end, it initializes a new object and then where I use me.print_password it just prints out Password 1: {generate_password}

Don't know exactly what I am doing wrong here, thanks for your help in advance.

CodePudding user response:

You need to use a hash character before your curly brackets (same notation as for double quotes):

puts %(Password: #{generate_password})
puts "Password: #{generate_password}"
  •  Tags:  
  • ruby
  • Related