Ruby

By | 16/09/2014

Shows the Ruby version installed in the system:

ruby -v

Ruby files uses extension rb. To run a rb file:

ruby file.rb

Comments

#This is a comment
puts "printing text" #just an example

=begin
multiple 
line comment
=end

Operations with strings

a = "string 1"
b = 'string 2'       # between '', variables will be ignored
puts a + b           #concatenate
"." * 10             #prints 10 dots '.'
s.split(char).first #get the part of the string before the "char"
s.split(char).last #get the part of the string after the "char"

Print vs puts

Puts add a \n at the end of the String.

print "text" 
puts "text"

Operations inside a puts using #{}

puts "2 + 3 is equal to #{2 + 3}."

User Input

gets by itself also obtain the \n from the input.

Chomp removes that \n.

to_i converts to integer

gets.chomp 
gets.chomp.to_i
stringvar.to_i //converts string to integer
stringvar.to_f //converts string to float
int.to_s // converts to String

Functions

def Function_Name(arg1,arg2)
   #code
   return var
end
def Function_Name(*args)
   arg1, arg2 = args
   #code
   return a, b
end
a, b = Function_Name(arg1, arg2)

Working with Files

Dir.entries(directory)
File.directory?(directory_path)
File.file?(file_path)
FileUtils.mkdir_p(path)
FileUtils.mv(source,destination,options)
FileUtils.cp(source,destination,options)

Working with Time

time = Time.now
time.month
time.min
time.sec
time.wday

Libraries:

exifr –  get exif information from images

fileutil – work with files and directories

http – interacts with http servers

 

Net::HTTP

References:

Net:HTTP Cheat Sheet

Net:HTTP Class info

 

 

References:

Learn Ruby

Install Ruby on Linux

Note: When following that guide, if “rvm requirements” fails because it doesn’t find the library libgdbm-dev, go to packages.debian.org and download the package directly to manual install it.