Request Dev Services »

cdev.co / Notes /

Dynamic vars and Math methods (Ruby intro tips)

A simple exercise to begin working with variables and math functions with Ruby.

Firstly let’s define Pi; which we’ll use to do math on. We don’t really have to create a class for this, but I like to as I typically turn it into one anyways later down the line when I expand or scale the code or app. Anyways, so.

class Pi
  Val = 3.14159
end

OK, so there’s Pi defined. Secondly, for use-case-scenario purposes let’s get the user to input a number between 1-6 and store that accepted inputted number into a variable that we’ll use later.

nr = -1
while nr < 0 || nr > 6
  print "Input a number between 1 and 6: "
  STDOUT.flush
  nr = gets.chomp.to_i
  angle = Pi::Val/nr
end

If the user inputs a numeric value not accepted by our while loop defined; ie outside of params 0-6, the question will be repeated asking the user to input the accepted number without the program continuing. This is handled by nr = gets.chomp.to_i

You’ll see I created a variable which is defining our defined Pi Value divided by the user accepted input value nr. Now, let’s print what we’ve gathered and use some of Rubys built in Math methods.

printf "Inserted number = %d. The angle = %f. Sine = %f\n. Cosine = %f\n, and Tangent
= %f\n", nr, angle, Math.sin(nr), Math.cos(nr), Math.tan(nr)

Sample terminal output screen shot.

About the Author
Cameron Cashwell Web Developer
I build websites, web apps, and software. Wanna work together? Let's chat about your project!

Leave a Reply

Be the First to Comment!

Notify of
avatar