Learn Core Ruby Concepts

Hello Everyone,

We all know basic concepts of Ruby, like classes, objects, methods etc. etc and we integrate this with the concept of rails beautifully.

In short I can say we all are very good at Ruby on Rails, and rails specially, but when it comes to Ruby, we are not that much confident tough.

In this Post of mine, we will cover all the important concepts of Ruby, some pure ruby code, and how we can apply this with Rails.

So let’s start learning the Core Ruby Concepts.

  • In RoR programming, most of the times we need to identify the type of string. We don’t know if the incoming string is a “Integer”, “Float”, “String”. To check that:
    y = Incoming String
    y.is_a?(Integer) => returns true or false
    y.is_a?(String) => returns the same
    y.is_a?(Fixnum) => -----#-------
    y.is_a?(Float) => -----#-------

    • We can also ask the variable exactly what class of variable it is using the class method:
      y = "Incoming String"
      y.class => returns String
      y = 10.25
      y.class => returns Float
      y = 10 => returns Fixnum
    • Sometimes we need to change the incoming string to say Integer (Note: It is for sure that in RoR application, when browser sends any parameter to any controller’s method, it will be string only), Float for further operations. To do that:
      x = "10.25"
      y = x.to_f
      p y.class => returns Float
      z = y.to_i
      p z.class => returns Fixnum
  • Variable type: Ruby has four types of variables:
    • Local variable [a-z] or _
    • Global Variable $
    • Instance variable @
    • Class variable @@

    To identify the type of variable, do:
    a = 10
    p defined?(a) => "local-variable"
    $b = "Puneet"
    p defined?($b) => "global-variable"

  • Metaprogramming: Metaprogramming is a technique in which code writes other code. The prefix Meta refers to Abstraction.
    • At a high level, metaprogramming is useful in working towards DRY principle (Don’t Repeat Yourself).
    • Metaprogramming is primarily about simplicity. One of the easiest ways to get a feel for metaprogramming is to look for repeated code and factor it out. Redundant code can be factored into functions; redundant functions or patterns can often be factored out through the use of metaprogramming.
Advertisement