# data[].attributes.body
salary = {  "starting" => 40000}

salary["mid-level"] = 60000

# data[].attributes.body
3.times do
  print 'Welcome '
end

5.times { print "Odelay! " }

5.times { |time|
  puts time
}
-----
0
1
2
3
4

# data[].attributes.body
they alter the variable for good use !

# data[].attributes.body
books["The deep end"]  = :abysmal
puts books
"The deep end"=>"abysmal"
puts books.length
3
puts books["The deep end"]
abysmal
books.keys show all key
books.values show all value

# data[].attributes.body
https://www.tutorialspoint.com/ruby/ruby_exceptions.htm

# data[].attributes.attachment_link.readable_text
The execution and the exception always go together. If you are opening a file, which does not exist, then if you did not handle this situation properly, then your program is considered to be of bad quality.

The program stops if an exception occurs. So exceptions are used to handle various type of errors, which may occur during a program execution and take appropriate action instead of halting program completely.

Ruby provide a nice mechanism to handle exceptions. We enclose the code that could raise an exception in a begin/end block and use rescue clauses to tell Ruby the types of exceptions we want to handle.

Syntax

begin
# -
rescue OneTypeOfException
# -
rescue AnotherTypeOfException
# -
else
# Other exceptions
ensure
# Always will be executed
end

Everything from begin to rescue is protected. If an exception occurs during the execution of this block of code, control is passed to the block between rescue and end.

For each rescue clause in the begin block, Ruby compares the raised Exception against each of the parameters in turn. The match will succeed if the exception named in the rescue clause is the same as the type of the currently thrown exception, or is a superclass of that exception.

In an event that an exception does not match any of the error types specified, we are allowed to use an else clause after all the rescue clauses.

Example

#!/usr/bin/ruby

begin
   file = open("/unexistant_file")
   if file
      puts "File opened successfully"
   end
rescue
      file = STDIN
end
print file, "==", STDIN, "\n"

This will produce the following result. You can see that STDIN is substituted to file because open failed.

#<IO:0xb7d16f84>==#<IO:0xb7d16f84>

Using retry Statement

You can capture an exception using rescue block and then use retry statement to execute begin block from the beginning.

Syntax

begin
   # Exceptions raised by this code will
   # be caught by the following rescue clause
rescue
   # This block will capture all types of exceptions
   retry  # This will move control to the beginning ofbegin end

Example

#!/usr/bin/ruby

begin
   file = open("/unexistant_file")
   if file
      puts "File opened successfully"
   end
rescue
   fname = "existant_file"
   retry
end

The following is the flow of the process −

An exception occurred at open.

Went to rescue. fname was re-assigned.

By retry went to the beginning of the begin.

This time file opens successfully.

Continued the essential process.

NOTE − Notice that if the file of re-substituted name does not exist this example code retries infinitely. Be careful if you use retry for an exception process.

Using raise Statement

You can use raise statement to raise an exception. The following method raises an exception whenever it's called. It's second message will be printed.

Syntax

raise

OR

raise "Error Message"

OR

raise ExceptionType, "Error Message"

OR

raise ExceptionType, "Error Message" condition

The first form simply re-raises the current exception (or a RuntimeError if there is no current exception). This is used in exception handlers that need to intercept an exception before passing it on.

The second form creates a new RuntimeError exception, setting its message to the given string. This exception is then raised up the call stack.

The third form uses the first argument to create an exception and then sets the associated message to the second argument.

The fourth form is similar to the third form but you can add any conditional statement like unless to raise an exception.

Example

#!/usr/bin/ruby

begin
   puts 'I am before the raise.'
   raise 'An error has occurred.'
   puts 'I am after the raise.'
rescue
   puts 'I am rescued.'
end
puts 'I am after the begin block.'

This will produce the following result −

I am before the raise.
I am rescued.
I am after the begin block.

One more example showing the usage of raise −

#!/usr/bin/ruby

begin
   raise 'A test exception.'
rescue Exception => e
   puts e.message
   puts e.backtrace.inspect
end

This will produce the following result −

A test exception.
["main.rb:4"]

Using ensure Statement

Sometimes, you need to guarantee that some processing is done at the end of a block of code, regardless of whether an exception was raised. For example, you may have a file open on entry to the block and you need to make sure it gets closed as the block exits.

The ensure clause does just this. ensure goes after the last rescue clause and contains a chunk of code that will always be executed as the block terminates. It doesn't matter if the block exits normally, if it raises and rescues an exception, or if it is terminated by an uncaught exception, the ensure block will get run.

Syntax

begin
   #.. process
   #..raise exception
rescue
   #.. handle error
ensure
   #.. finally ensure execution
   #.. This will always execute.
end

Example

begin
   raise 'A test exception.'
rescue Exception => e
   puts e.message
   puts e.backtrace.inspect
ensure
   puts "Ensuring execution"
end

This will produce the following result −

A test exception.
["main.rb:4"]
Ensuring execution

Using else Statement

If the else clause is present, it goes after the rescue clauses and before any ensure.

The body of an else clause is executed only if no exceptions are raised by the main body of code.

Syntax

begin
   #.. process
   #..raise exception
rescue
   # .. handle error
else
   #.. executes if there is no exception
ensure
   #.. finally ensure execution
   #.. This will always execute.
end

Example

begin
   # raise 'A test exception.'
   puts "I'm not raising exception"
rescue Exception => e
   puts e.message
   puts e.backtrace.inspect
else
   puts "Congratulations-- no errors!"
ensure
   puts "Ensuring execution"
end

This will produce the following result −

I'm not raising exception
Congratulations-- no errors!
Ensuring execution

Raised error message can be captured using &dollar;! variable.

Catch and Throw

While the exception mechanism of raise and rescue is great for abandoning the execution when things go wrong, it's sometimes nice to be able to jump out of some deeply nested construct during normal processing. This is where catch and throw come in handy.

The catch defines a block that is labeled with the given name (which may be a Symbol or a String). The block is executed normally until a throw is encountered.

Syntax

throw :lablename
#.. this will not be executed
catch :lablename do
#.. matching catch will be executed after a throw is encountered.
end

OR

throw :lablename condition
#.. this will not be executed
catch :lablename do
#.. matching catch will be executed after a throw is encountered.
end

Example

The following example uses a throw to terminate interaction with the user if '!' is typed in response to any prompt.

def promptAndGet(prompt)
   print prompt
   res = readline.chomp
   throw :quitRequested if res == "!"
   return res
end

catch :quitRequested do
   name = promptAndGet("Name: ")
   age = promptAndGet("Age: ")
   sex = promptAndGet("Sex: ")
   # ..
   # process information
end
promptAndGet("Name:")

You should try the above program on your machine because it needs manual interaction. This will produce the following result −

Name: Ruby on Rails
Age: 3
Sex: !
Name:Just Ruby

Class Exception

Ruby's standard classes and modules raise exceptions. All the exception classes form a hierarchy, with the class Exception at the top. The next level contains seven different types −

Interrupt

NoMemoryError

SignalException

ScriptError

StandardError

SystemExit

There is one other exception at this level, Fatal, but the Ruby interpreter only uses this internally.

Both ScriptError and StandardError have a number of subclasses, but we do not need to go into the details here. The important thing is that if we create our own exception classes, they need to be subclasses of either class Exception or one of its descendants.

Let's look at an example −

class FileSaveError < StandardError
   attr_reader :reason
   def initialize(reason)
      &commat;reason = reason
   end
end

Now, look at the following example, which will use this exception −

File.open(path, "w") do |file|
begin
   # Write out the data ...
rescue
   # Something went wrong!
   raise FileSaveError.new(&dollar;!)
end
end

The important line here is raise FileSaveError.new(&dollar;!). We call raise to signal that an exception has occurred, passing it a new instance of FileSaveError, with the reason being that specific exception caused the writing of the data to fail.

# data[].attributes.attachment_link.description
The execution and the exception always go together. If you are opening a file, which does not exist, then if you did not handle this situation properly, then your program is considered to be of bad quality. The program stops if an exception occurs.

# data[].attributes.body
ratings = Hash.new {0}

books.values.each { |rate|
ratings[rate] += 1
}
puts books.values
puts ratings

------------
splendid
abysmal
mediocre
mediocre
{"splendid"=>1, "abysmal"=>1, "mediocre"=>2}

# data[].attributes.body
def count_plays(year)
s = get_shakey

s["William Shakespeare"]
.select { |k, v|
v["finished"] == year
}.each { |key, val|
puts val["title"]
}.count
end

puts count_plays(1591)

# data[].attributes.body
def print_plays(year_from, year_to)
get_shakey["William Shakespeare"]
.select { |k, v|
year_from <= v["finished"] &&
year_to   >= v["finished"]
}.each { |k, v|
puts "#{v["title"].ljust(30)} #{v["finished"]}"
}
end
print_plays(1600, 1605)

# data[].attributes.attachment_link.readable_text
Ruby is a programming language from Japan which is revolutionizing software development.

The beauty of Ruby is found in its balance between simplicity and power.

You can type some Ruby code in the editor and use these buttons to navigate:

Run → Executes the code in the editor

Copy → Copies the example code to the editor

Next → Allows you to go to the next lesson

Back → Allows you to return to the previous lesson

Clear → Clears the editor

Click on Next to start learning.

# data[].attributes.attachment_link.description
Ruby is a programming language from Japan which is revolutionizing software development. The beauty of Ruby is found in its balance between simplicity and power.

# data[].attributes.body
5     <= 10     # => true
'abc' == 'def'  # => false
true            # => true
123456          # => true
0               # => true
nil             # => false
'xyz'.empty?    # => false
'a' > 5         # => error:
                # comparison of String with
                # Numeric failed

# data[].attributes.body
class Blurb
  attr_accessor :content, :time, :mood

  def initialize(mood, content="")
    @time    = Time.now
    @content = content[0..39]
    @mood    = mood
  end

  def moodify
    if    @mood == :sad
      return ":-("
    elsif @mood == :happy
      return ":-)"
    # Add other moods here
    end

    # The default mood
    ":-|"
  end
end

class Blurbalizer
  def initialize(title)
    @title  = title
    @blurbs = []
  end

  def add_a_blurb(mood, content)
    @blurbs << Blurb.new(mood, content)
  end

  def show_timeline
    puts "Blurbalizer: #{@title} has #{@blurbs.count} Blurbs"

    @blurbs.sort_by { |t|
      t.time
    }.reverse.each { |t|
      puts "#{t.content.ljust(40)} #{t.mood} #{t.time}"
    }
  end
end
myapp = Blurbalizer.new "The Big Blurb"
myapp.add_a_blurb(:happy,"okokok")
myapp.add_a_blurb(:sad,"not okokok")

myapp.show_timeline

# data[].attributes.body
# I am a single line comment.

=begin

I am a multi line comment. I can take as many lines as needed.

=end

# data[].attributes.body
# Integer
valuex = 1

# Float
valuey = 1.2

# data[].attributes.body
puts "codecademy".upcase# CODECADEMY

puts "Codecademy".downcase# codecademy

# data[].attributes.body
age = 30

print "Hi, my name is Cody, and I am #{age} years old"# "Hi, my name is Cody, and I am 30 years old"

# data[].attributes.body
print "Type your name and press Enter: "name = gets.chomp

puts "My name is #{name}!"

# data[].attributes.body
print "Enter a number"

number = gets.to_i
unless number > 10
puts "number is less than 10."
end

# data[].attributes.body
data = [3, 6, 9, 12]

data.each do |num|
puts "The number is: #{num}"
end

# data[].attributes.body
for i in 1..10
next if i % 2 == 0
puts i
end

# data[].attributes.body
i = 1

while i <= 3 do
puts "Message number #{i}"
i = i + 1
end

# data[].attributes.body
# Inclusive
(3..5).each do |i|
puts i
end# Output:
# 3
# 4
# 5

# Exclusive
(3...5).each do |i|
puts i
end
# Output
# 3
# 4

# data[].attributes.body
num = 1

loop do
puts "We are in the loop!"
num += 1
break if num > 3
end
puts "We have exited the loop!"

# data[].attributes.body
i = 1

until i == 4 do
puts "Message number #{i}"
i = i + 1
end

# data[].attributes.body
for i in 1..3 do
puts "Message number #{i}"
end

# data[].attributes.body
multi_array = [[0,1,2,3],[4.5, true, "hi"]]

# Accessing the array at index 1
puts multi_array[1] # => [4.5, true, "hi"]

# Accessing the element at index 0 within the array at index 1
puts multi_array[1][0] # => 4.5

# data[].attributes.body
puts "Keanu" <=> "Adrianna"
# The first letters of each word are compared in ASCII order and since "K" comes after "A", 1 is printed.

puts 1 <=> 2 # -1

puts 3 <=> 3 # 0

#<=> can also be used inside of a block and to sort values in descending order:
my_array = [3, 0, 8, 7, 1, 6, 5, 9,4]
my_array.sort! { |first_num, second_num| second_num <=> first_num }
print my_array
#Output => [9, 8, 7, 6, 5, 4, 3, 1, 0]

# data[].attributes.body
def extra_curriculars(*clubs)
clubs.each { |club| puts "After school, I'm involved with #{club}" }
end

extra_curriculars("chess club", "gymnastics", "anime club", "library services")

# data[].attributes.body
my_bologna = {
:first_name => "Oscar",
:second_name => "Meyer",
:slices => 12}

puts my_bologna[:second_name] # => Meyer

# data[].attributes.body
olympic_trials = {  Sally: 9.58,  John: 9.69,  Bob: 14.91}

olympic_trials.select { |name, time| time <  10.05 }

# data[].attributes.body
eren_jaeger = {
age: 15,
enemy: "titans",
branch: "Survey Corps"
}
eren_jaeger.each_key { |key| puts key }
eren_jaeger.each_value { |value| puts value }

# data[].attributes.body
tv_show = "Bob's Burgers"

case tv_show  when "Archer"
puts "I don't like the voice of Archer."
when "Bob's Burgers"
puts "I love the voice of Bob Belcher."
else
puts "I don't know who voices this cartoon."

end

# data[].attributes.body
puts "A".respond_to?(:push)
# => false
puts "A".respond_to?(:next)
# => true

# data[].attributes.body
a = true

b = false

c = true

puts a || b

#Output => true

puts b || a

#Output => true

puts a && c

#Output => true

puts a && b

#Output => false

# data[].attributes.body
a = true
b = false
c = true

puts a || b
#Output => true
puts b || a
#Output => true
puts a && c
#Output => true
puts a && b
#Output => false

# data[].attributes.body
"B".upto("F") { |letter| print letter, " " }# => B C D E F

5.downto(0) { |num| print num, " " }# => 5 4 3 2 1 0

# data[].attributes.body
boyfriend = nil #OR FALSE

boyfriend ||= "Jimmy Jr."

boyfriend ||= "Josh"

puts boyfriend# => "Jimmy Jr."

# data[].attributes.body
array = [1, 2, 3]array << 4print array#Output => [1, 2, 3, 4]

puts "Hello," << " welcome to Codecademy."#Output => Hello, welcome to Codecademy.

# data[].attributes.body
puts "This number is even!" if num % 2 == 0

# data[].attributes.body
proc_test = Proc.new { puts "I am the proc method!" }lambda_test = lambda { puts "I am the lambda method!"}

proc_test.call # => I am the proc method!lambda_test.call # => I am the lambda method!

# data[].attributes.body
def proc_demo_method
proc_demo = Proc.new { return "Only I print!" }
proc_demo.call  "But what about me?"
# Never reachedend

puts proc_demo_method

# Output # Only I print!

def lambda_demo_method
lambda_demo = lambda { return "Will I print?" }  lambda_demo.call  "Sorry - it's me that's printed."

end

puts lambda_demo_method

# Output

# Sorry - it's me that's printed.

# data[].attributes.body
def proc_demo_method
proc_demo = Proc.new { return "Only I print!" }
proc_demo.call  "But what about me?"
# Never reachedend

puts proc_demo_method
# Output # Only I print!

def lambda_demo_method
lambda_demo = lambda { return "Will I print?" }  lambda_demo.call  "Sorry - it's me that's printed."
end

puts lambda_demo_method
# Output
# Sorry - it's me that's printed.

# data[].attributes.body
first_arr = [3, 4, 5]
second_arr = first_arr.collect { |num| num * 5 }

print second_arr
#Output => [15, 20, 25]

# data[].attributes.body
def yield_test
puts "I'm inside the method."
yield
puts "I'm also inside the method."end

yield_test { puts ">>> I'm butting into the method!" }
#Output
# I'm inside the method.
# >>> I'm butting into the method.
# I'm also inside the method.

# data[].attributes.body
square = Proc.new { |x| x ** 2 }

puts [2, 4, 6].collect!(&square)
# => [4, 16, 36]

# data[].attributes.body
class Trip
def initialize(duration, price)
@duration = duration
@price = price  endend

class Cruise < Trip
def initialize(duration, price)
super
end

end

spain_backpacking = Trip.new(14, 800.00)carnival = Cruise.new(7, 2400.00)

# data[].attributes.body
class Trip
def initialize(duration, price)
@duration = duration
@price = price  endend

class Cruise < Trip
   def initialize(duration, price)
   super
   end
end

spain_backpacking = Trip.new(14, 800.00)carnival = Cruise.new(7, 2400.00)

# data[].attributes.body
puts Math::PI# => 3.141592653589793

# data[].attributes.body
require 'date'

puts Date.today# => 2020-04-16

# data[].attributes.body
module MyPizza
FAVE_TOPPING = "Buffalo Chicken"
end

# data[].attributes.body
https://www.codecademy.com/learn/learn-ruby/modules/learn-ruby-introduction-to-ruby-u/cheatsheet

# data[].attributes.attachment_link.readable_text
In Ruby, a variable is a place to store values of almost any type including Integer, Boolean, String, Array, and Hashes.

Each variable has its own name which cannot begin with a capital letter or a number and we use the equal sign for assigning a value to that variable.

The variable declaration does not require that you mention a specific data type.

The following program declares myvar variable and assigns the value 48.

# data[].attributes.attachment_link.title
Learn Ruby: Introduction to Ruby Cheatsheet | Codecademy

# data[].attributes.attachment_link.description
In Ruby, a variable is a place to store values of almost any type including Integer, Boolean, String, Array, and Hashes. Each variable has its own name which cannot begin with a capital letter or a number and we use the equal sign for assigning a value to that variable.

# data[].attributes.body
aFile = File.new("filename", "mode")
   # ... process the file
aFile.close

# data[].attributes.body
File.open("filename", "mode") do |aFile|
   # ... process the file
end

# data[].attributes.body
aFile = File.new("input.txt", "r")
if aFile
   content = aFile.sysread(20)
   puts content
else
   puts "Unable to open file!"
end

# data[].attributes.body
aFile = File.new("input.txt", "r+")
if aFile
   aFile.syswrite("ABCDEF")
else
   puts "Unable to open file!"
end

# data[].attributes.body
aFile = File.new("input.txt", "r+")
if aFile
   aFile.syswrite("ABCDEF")
   aFile.each_byte {|ch| putc ch; putc ?. }
else
   puts "Unable to open file!"
end

# data[].attributes.body
arr = IO.readlines("input.txt")
puts arr[0]
puts arr[1]

# data[].attributes.body
IO.foreach("input.txt"){|block| puts block}

# data[].attributes.body
# Rename a file from test1.txt to test2.txt
File.rename( "test1.txt", "test2.txt" )

# data[].attributes.body
# Delete file test2.txt
File.delete("test2.txt")

# data[].attributes.body
file = File.new( "test.txt", "w" )
file.chmod( 0755 )

# data[].attributes.body
File.open("file.rb") if File::exists?( "file.rb" )

# data[].attributes.body
# This returns either true or false
File.file?( "text.txt" )

# data[].attributes.body
# a directory
File::directory?( "/usr/local/bin" ) # => true

# a file
File::directory?( "file.rb" ) # => false

# data[].attributes.body
File.readable?( "test.txt" )   # => true
File.writable?( "test.txt" )   # => true
File.executable?( "test.txt" ) # => false

# data[].attributes.body
File.zero?( "test.txt" )      # => true

# data[].attributes.body
File.size?( "text.txt" )     # => 1002

# data[].attributes.body
File::ftype( "test.txt" )     # => file

# data[].attributes.body
File::ctime( "test.txt" ) # => Fri May 09 10:06:37 -0700 2008
File::mtime( "text.txt" ) # => Fri May 09 10:44:44 -0700 2008
File::atime( "text.txt" ) # => Fri May 09 10:45:01 -0700 2008

# data[].attributes.body
Navigating Through Directories
Dir.chdir("/usr/bin")

puts Dir.pwd # This will return something like /usr/bin

# data[].attributes.body
puts Dir.entries("/usr/bin").join(' ')

Dir.foreach("/usr/bin") do |entry|
   puts entry
end

Dir["/usr/bin/*"]

# data[].attributes.body
Dir.mkdir("mynewdir")

Dir.mkdir( "mynewdir", 755 )

Dir.delete("testdir")

# data[].attributes.body
require 'tmpdir'
   tempfilename = File.join(Dir.tmpdir, "tingtong")
   tempfile = File.new(tempfilename, "w")
   tempfile.puts "This is a temporary file"
   tempfile.close
   File.delete(tempfilename)

require 'tempfile'
   f = Tempfile.new('tingtong')
   f.puts "Hello"
   puts f.path
   f.close