ruby - Unexpected output in string format with instance variables -


i writing console application , want display prompt command number (i.e variable increased every time user presses enter).

expected output:

[0] app_name > 1 [1] app_name > 2 [2] app_name > 

here code:

class prompt   attr_accessor :format, :string, :prompt, :index   def initialize     init_vars     @format = "[%s] %s > "     @string = [@index, "app_name"]     @prompt = @format % @string   end   def init_vars     @index = 0   end   def update_prompt     @index += 1     @prompt = @format % @string   end end  require 'readline'  prompt = prompt.new while last = readline.readline(prompt.prompt)   prompt.update_prompt   puts prompt.index end 

output:

[0] app_name > 1 [0] app_name > 2 [0] app_name > 

when change line:

@prompt = @format % @string 

to:

@prompt = @format % [@index, "app_name"] 

i plan use internal framework, , user specify @format , @string , produce prompt. believe changing line above not work.

may explain doing wrong?

here working code:

class prompt    attr_accessor :format, :string, :prompt, :index    def initialize     @index = -1     @format = "[%d] %s > "     update_prompt   end    def update_prompt     @index += 1     @string = @index, "app_name"     @prompt = @format % @string   end  end  require 'readline'  prompt = prompt.new while last = readline.readline(prompt.prompt)   prompt.update_prompt   #de puts prompt.index end 

output expected:

[0] app_name >  [1] app_name >  [2] app_name >  [3] app_name >  [4] app_name >  [5] app_name >  [6] app_name >  

the @string being frozen @ @index == 0 needed updated, @index was. thought @index update, , reference being stored in @string, value being stored... not reference updated. i'm curious why, i've fixed code regardless.


knowing know how @string handled...

here smaller version:

class prompt    attr_accessor :format, :string, :prompt, :index    def initialize     @index = -1     @format = "[%d] %s > "     update_prompt   end    def update_prompt     @prompt = @format % [ @index += 1, "app_name" ]   end  end 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -