user1865578
user1865578

Reputation: 45

Ruby programming - unable to initialize instance variable with default values

In the code below, I have given a default value for the accountNumber for when it is not called with a particular value but that value is not recognized by the code, why is that?

class BankAccount
   CONST=0100

   def interest_rate
        @@interest_rate = 0.2
   end

   def accountNumber
        @accountNumber
   end

   def accountNumber=(value = 10)
        puts value
        @accountNumber = value
   end
end

When I call the accountNumber= method as below with no arg, I expect it to puts "10" but it is not putting out the default value...

account1 = BankAccount.new()
puts account1.accountNumber=()

Upvotes: 1

Views: 180

Answers (4)

Jörg W Mittag
Jörg W Mittag

Reputation: 369604

You are assigning an empty expression () to the setter method. In Ruby, empty expressions evaluate to nil (what else would they evaluate to anyway?), therefore you are assigning nil.

Upvotes: 0

jboursiquot
jboursiquot

Reputation: 1271

ck3g's answer is on point. Just set up your defaults in your initializer. What that in mind, you could simplify your class to just

class BankAccount
   CONST=0100
   attr_accessor :accountNumber

   def initialize(accountNumber = 10)
     @accountNumber = accountNumber
   end

   def interest_rate
     @@interest_rate = 0.2
   end
end

This lets ruby handle the getter and setter for your accountNumber attribute automatically.

Upvotes: 4

sawa
sawa

Reputation: 168259

I cannot be fully sure, but it seems to be some irregularity due to the method name ending with =. That type of methods do not seem to accept default values correctly. When you change the method name to set_account_number, then it will work.

Upvotes: 1

ck3g
ck3g

Reputation: 5929

account1.accountNumber=(10)

Is the same as

account1.accountNumber = 10

It's weird to use account1.accountNumber = without passing value.

If you need default value set it inside constructor.

def initialize
  @accountNumber = 10
end

then

account1 = BankAccount.new
puts account1.accountNumber # => 10

Upvotes: 5

Related Questions