0

I have referred to this question on the forum to do this: Using a string as a variable at run time

This is what I have:

def create_account
  puts "Username?"
  account_name=gets.chomp
  account_name_var=#account_name as variable

  #Sets array as variable
  string_values = { }
  some_string = [:some_string]       # parameter was, say "Hello"
  string_values[some_string] = account_name
  string_values                            # { 'Hello' => 42 }
  account_name_var = string_values[some_string]
  account_name_var                              # 42

  account_name_var=BankAccount.new(account_name, "open")
  account_name_var=BankAccount.new(account_name, "open")
end

create_account
create_account
# pablo=BankAccount.new("pablo", "open")
# theo=BankAccount.new("theo", "open")
make_transfer(name, name2, 10)

But I get

: undefined local variable or method name for main:Object (NameError) on the line make_transfer(name, name2, 10)

.

So name is not set as a variable when I input name as the first username and name2 as the second username.

Community
  • 1
  • 1
Pabi
  • 946
  • 3
  • 16
  • 47
  • 3
    What if you enter `foobar` as a first username? Do you expect the code files to magically change to reflect this unexpected input? – Sergio Tulentsev Jul 13 '15 at 13:43

1 Answers1

2

Just return the BankAccount instance from your method and assign it to a variable:

def create_account
  puts "Username?"
  account_name = gets.chomp
  BankAccount.new(account_name, "open")
end

account_1 = create_account
account_2 = create_account
make_transfer(account_1, account_2, 10)

Or, use a Hash to store the accounts by name:

@accounts = {}

account = create_account
@accounts[account.name] = account

account = create_account
@accounts[account.name] = account

make_transfer(@accounts['pablo'], @accounts['theo'], 10)
Stefan
  • 109,145
  • 14
  • 143
  • 218