Home > front end >  How to call an array outside of a function in SketchUp Ruby
How to call an array outside of a function in SketchUp Ruby

Time:02-24

I am building a custom Decimal Degrees (DD) to Decimal Minute Seconds (DMS) function to use in SketchUp's Ruby. Below is my script.

arg1 = 45.525123

def DMS(arg1)
    angle = arg1
    deg = angle.truncate()
    dec = (angle - angle.truncate()).round(6)
    totalsecs = (dec * 3600).round(6)
    mins = (totalsecs / 60).truncate()
    secs = (((totalsecs / 60) - (totalsecs / 60).truncate()) * 60).round(2)
    array = [deg, mins, secs]
end

DMS(arg1)

So far so good, if you ran this script in Ruby, you'd probably end up with an array that gives you [45, 31, 30.44]

I then try to add a line of code which assigns that array under a different name. Here is the new code with the extra line.

arg1 = 45.525123

def DMS(arg1)
    angle = arg1
    deg = angle.truncate()
    dec = (angle - angle.truncate()).round(6)
    totalsecs = (dec * 3600).round(6)
    mins = (totalsecs / 60).truncate()
    secs = (((totalsecs / 60) - (totalsecs / 60).truncate()) * 60).round(2)
    array = [deg, mins, secs]
end

DMS(arg1)
bearingarray = array

If you ran the second block of code however, you would end up with an array of [1, 2, 3].

My expectation was that I would get that exact same values in the array, but under the different name.

What has gone wrong? What should I do to fix it?

Thanks for your help!

CodePudding user response:

Your second code block is wrong, if you run it you get undefined local variable or method array for main:Object.

You are probably running the code in an interactive session and you have defined array before, take into account array is local to DMS function.

I would say what you want is to do

arg1 = 45.525123

def DMS(arg1)
  angle = arg1
  deg = angle.truncate()
  dec = (angle - angle.truncate()).round(6)
  totalsecs = (dec * 3600).round(6)
  mins = (totalsecs / 60).truncate()
  secs = (((totalsecs / 60) - (totalsecs / 60).truncate()) * 60).round(2)
  array = [deg, mins, secs]
end


bearingarray = DMS(arg1)

Assigning the output of DMS to bearingarray

  • Related