Skip to content

Instantly share code, notes, and snippets.

@prabhakaran9397
Last active May 10, 2017 12:35
Show Gist options
  • Save prabhakaran9397/c3c8ad2c75e959ace98242f89d47b68a to your computer and use it in GitHub Desktop.
Save prabhakaran9397/c3c8ad2c75e959ace98242f89d47b68a to your computer and use it in GitHub Desktop.
Beginning Ruby - 1

[10-05-2015] [Prabhakaran S]

Beginning Ruby - 1

Points to remember

puts to print, gets to scan

ARGV is the array that contains arguments passed.

$0 is the file name, infact the first argument

$stdin, $stdout, $env all are there!

Normal math operations Addition (+) Subtract (-) Division (/) Multiplication (*) Modulo (%) - No negative modulo Exponent (**) Boolean - The C way (<=>) -1, 0, 1 locate smallest value

a, b, c = [1, 2, 3]
a, b, c = 1, 2, 3
# Both are same

Everying is an object in Ruby

1.next or 1.method('next').call

.respond_to?(method_name) tells if method exists for that object

self find where am I - Its an object again!

Object.class tell me the class name

Object.methods list all the methods

No need of brackets! Object.method1.method2...

obj.add(1, 2)
obj.add 1, 2

Method

Method creating procedure, use snake_casing

def method_name(arg1, arg2)
	# do whatever
end

The return specifies the object to be returned to the caller when the method has done its work. If no return, returns the object created by the last line in the method. A method must always return exactly one object.

default values can be used in the arguments like C++, python

* - splat operator - converts parameters to array and array to paramaters

def add(a_number, another_number, options = {})
  sum = a_number + another_number
  sum = sum.abs if options[:absolute]
  sum = sum.round(options[:precision]) if options[:round]
  sum
end

puts add(1.0134, -5.568)
puts add(1.0134, -5.568, absolute: true)
puts add(1.0134, -5.568, absolute: true, round: true, precision: 2)

Control Flow - If

if cond ... elsif cond ... else ... end

Ruby supports ternary operator cond ? do_if_true : do_if_false

0 is true in Ruby!

Control Flow - Loop

loop do do_inside end <=> loop { do_inside } Ruby iterates with a class called Enumerator .times, .each, .each_with_index converts them to enumerators

(1..5).each do |counter| puts "iteration #{counter}" end

for i in Array do_something end

Some notable classes String Array Hash

String

a = "Hey" # Needs computation inside - String interpolation
b = "#{a}, How are you?" # This is interpolation
a = 'Hey'

By the way # is the comment

a, b are all of class String

Everything cannot be documented, but few examples.

String.split [delimiter] # convert String to Array

String1 << + .concat String2 # Concatenation << also works for Array

.sub regex replace # first occurence - regex "/pattern/" .gsub regex replace # all occurences .match regex starting # first occurence

Array

[] or Array.new Supports negative indexing [start_index, length] [start_index, end_index]

Array.map do |e| e+1 end # Transformation of array - .collect, .each Array.select do |e| condition end # Filtering of array - .reject, .find .find matches only the first .inject has a variable retaining value for all the iteration. similarly .reduce Array.inject do |accumulator, element| do_something end

Similarly .delete, .delete_if

Hash

mehash = {'Monday' => 'First Day', 'Friday' => 'Fun Day' }
mehash = Hash['Monday', 'First Day', 'Friday', 'Fun Day']
mehash = Hash.new [default_value]
mehash.each do |key, value| do_something end

Class

.class tell me the class name .new creates an instance

$var is global variable @var is alive only within its block @@var is alive and visible to the whole class

def a=(a) # Setter method
  @a=a
end
attr_writer :a

def a # Getter method
  @a
end
attr_reader :a

Inheritance / Derives - @@var are visible for them

class Mom
end

class Son < Mom
end

self.method_name accessible by class name (no need of objects)

modules can be included or extended include - make it accessible for instances extend - make it accessible for classes

If module has modules inside, just define the rules for each module.

module ConcernExample
  def self.[extended, included](base)
    base.[extend, include](module_name)
  # base.send(:[extend, include], module_name)
  end
  ...
end

This is how you include/exclude a module

class Something
  [extend, include] ConcernExample
end

Variables in the module should start with capital letter

:: is used to access class, methods, variables inside the modules

Lamdas

Function but without a name!

lambda do |a| p "Hey! #{a}" end.call 'Args passed here'
# Usual way
l = lambda do |a| p "Hey! #{a}" end
l.call "Args passed here"

Blocks

def s(a)
  yield(a)
end
s('Args passed here') do |a| puts "[#{a}]" end

File I/O

mode = 'r+' # 'r', 'w', 'r+', 'w+'
file = File.open("list.txt", mode)
puts file.inspect
puts file.read # to read
file.puts "Hello" # to write
file.close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment