1

I'm new to ruby. Is there a way to shorten this code("increment var#")? I've created 26 entry for an alphabet.

require 'tk'
dis = { 'padx' =>5, 'pady' =>5}
root = TkRoot.new {title "Alphabet"}
elpar = {'height' => 25, 'width' => 25}
f1 = TkFrame.new{
    relief 'sunken'
    borderwidth 1
    background "black"
    height 800
    width 800
    dis
    pack
    }
f1.place('x' => 0, 'y' => 0)

el00 = TkEntry.new(f1)
el01 = TkEntry.new(f1)
el02 = TkEntry.new(f1)
          to             # Can I use loop here to shorten it?
el26 = TkEntry.new(f1)   


var1 = TkVariable.new
           to            #(1)
var2 = TkVariable.new


el00.textvariable = var1
var1.value = "A"
el00.place(elpar)
el00.place('x' => 0, 'y' => 0)
          to             #
el26.textvariable = var26
var26.value = "Z"
el26.place(elpar)
el26.place('x' => 728, 'y' => 0)

Tk.mainloop

(1) I've tried using loop here

  x = 1
  while x < 27
    "var#{x}"=TkVariable.new         # var1 is still undefined local variable if I use a loop.  
    "var" + x.to_s=TkVariable.new    # another variation that i've tried 
     x += 1
  end

Is there a way to shorten it? My codes are just an increment of 1?

Thanks, Jim

1

1 Answer 1

1

You could just store the entries in an array:

entries = Array.new(26) { TkEntry.new(f1) }

Then read your entries:

entries[0] #=> first entry
entries[1] #=> second entry

Use the character range from A to Z to set the arguments:

('A'..'Z').each_with_index do |character, index|
  variable = TkVariable.new
  variable.value = character
  entries[index].textvariable = variable 
  entries[index].place(elpar)
  entries[index].place('x' => 0, 'y' => 0)   # you did not explain how to calculate this
end
Sign up to request clarification or add additional context in comments.

1 Comment

Hi spickermann, Thank you so much for your immediate response.. :D the codes you gave me, save me a lot of lines. The entries[index].place('x' => 0, 'y' => 0) it is an increment of 27 in its horizontal plane. By the way, when I tried changing ('A'..'Z') to a range of integer it didn't work? I'll explore more about this "each" iterator. Thanks again, Jim

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.