DEV Community

Thierry Chau
Thierry Chau

Posted on

TIL the basics of Ruby

I dived right into learning Ruby these past few days, and it's been pretty exciting! I've learned a lot and here are a few bullet points to organize my thoughts about this journey

  • You can create your own classes in Ruby, and methods associated with it. There are instance methods and class-level methods. This is how it is done:
class New_class
  attr_accessor :attribute

  def method_class
    return #some method
  end

end
Enter fullscreen mode Exit fullscreen mode

:attribute is a Symbol. They act like Strings but are unique, great for using as a key in Hash.

  • Ruby has a class Date that needs to be loaded. It allows manipulations on dates
require Date

pp Date.today
pp Date.parse("3rd Feb 2001")
Enter fullscreen mode Exit fullscreen mode

Substracting two dates gives a Rational! It helps with getting accurate results as opposed to ‘Float’ and ‘Decimal’ objects which can produce inaccurate results because computers have limited memory. For this reason financial payment services always use Integers in their calculations.

  • Ruby has a large community with many programs available, called "gems". They can be loaded more easily with a "Gemfile" (no extension) with the following code:
source "https://rubygems.org"
# the following are examples of gem available
gem "activesupport"
gem "awesome_print"
gem "pry-byebug"
Enter fullscreen mode Exit fullscreen mode

These are then installed all at once by typing bundle install in the terminal.

  • Github is an amazing ressource for programming. I have an IDE readily available online, it saves and keeps track of all my programming. I'm barely scratching the surface of it right now, and I'm sure there is much more to it.

  • rand is based off the Mersenne Twister algorithm. It generates random numbers from a seed value. This seed value can be called with srand, and by default is based on the computer's clock. For a given srand, rand will generate the same sequence of numbers. The rand is random enough for lower stake application, but can technically be predicted if one can observe 624 numbers in the sequence! For cryptography, the module SecureRandom is the way to go!
    .sample uses rand to pick a random element in an array.

  • gsub can be used with a block. I learned this while trying to use a Hash for encrypting and decrypting a message:

def encrypting(secret)
  code = {
    "a" => "1",
    "e" => "2",
    "i" => "3",
    "o" => "4",
    "u" => "5"}
  return secret.gsub(/[aeiou]/i) { |match| code.fetch(match.downcase) }
end
Enter fullscreen mode Exit fullscreen mode

Top comments (0)