Man With Code 👨‍💻

In which I occasionally teach you things.

Tag: numbers

Programming With Ruby Episode 5, Numbers

Series: Ruby Programming

Covered in This Episode
  • Numbers
  • Expressions
  • Types of Numbers
  • Constants (New type of variable!)
  • Doing something a number of times
Transcript Hello Everyone and Welcome to Programming With Ruby Episode 5, Numbers. Its sitll presented by me, Tyler. And brought to you by manwithcode.com In this episode I will be talking about numbers in Ruby. I will go over expressions, the different types of numbers, I will introduce a new variable type called a constant, and will show you how to repeat an action a certain number of times in Ruby. Lets get started! Pop open you Command prompt or Terminal and start Interactive Ruby. If you have forgotten, just enter 'irb'. First item is expressions. [sourcecode language="ruby"] 2 + 2 #=> 4 2 - 2 #=> 0 3 * 3 #=> 9 6 / 3 #=> 2 2 ** 5 #=> 5 [/sourcecode] expressions with variables work in the same way [sourcecode language="ruby"] x = 5 5 * x #=> 25 x ** 4 #=> 625 [/sourcecode] If you want to do math on a variable and set the value of the variable to the result use: [sourcecode language="ruby"] x = 5 x *= 2 #=> x = 10 x -= 4 #=> x = 6 x /= 6 #=> x = 1 [/sourcecode] In Ruby there are 3 different types of numbers. Fixnum, which are 32-bit numbers. Floats, which are numbers with a value after the decimal point. Bignums which are numbers larger than 32-bits. [sourcecode language="ruby"] 5.class #=> Fixnum 0.421.class #=> Float 999999999999 #=> Bignum [/sourcecode] In Ruby it is possible to separate up larger numbers to improve readability in the code. Simply place in underscores [sourcecode language="ruby"] 1_000_000 #=> 1000000 [/sourcecode] Lets say you are writing some code and you need to do something a certain number of times. Use this code: [sourcecode language="ruby"] 2.times do |x| puts x end #=> 0 #=> 1 [/sourcecode] That wraps it up for this episode. If you have any questions or comments, leave a comment in the comment box below. Or email me at [email protected] Don't forget to donate. The button is to the right of this video. Thanks for watching. Goodbye
Keep reading...