Ruby Files

Objetives

File Class

# Create a file Object

# Initialize a File Object
file = File.new("example.txt")
# file = File.open("example.txt")

# read / handle
p file.read
# p file.readline
# p file.readlines

# Close File
file.close

# Asked is open
file.closed?

Open Modes

# Syntaxes

file = File.open("yourfilename.txt", "mode")
# Read Only 'r'

file = File.open('myfile.txt', 'r')
# Write only 'w'

file = File.open('myfile.txt', 'w')
# Append only 'a'

file = File.open('myfile.txt', 'a')
# Read - write permission 'r+'

file = File.open('myfile.txt', 'r+')
# Write - read permission 'w+'

file = File.open('myfile.txt', 'w+')
# Append - Read & Write permissions 'a+'

file = File.open('myfile.txt', 'a+')

Open with Blocks

# Read files

File.open('myfile.txt', 'r') do |file|
 while line = file.gets
  puts line
 end
end
# Write files

File.open('file.txt', 'w') do |file|
 file.write("Created new file!")
end
# Append files

File.open('file.txt', 'a') do |file|
 file.write("Created new file!")
end

Arguments Values

ARGV

# Syntaxes

ruby argv.rb these are elements in the argv array

# arguments => ["these", "are", "elements", "in", "the", "argv", "array"]
# Example

input_array = ARGV
puts input_array.size
puts input_array.to_s

# Another example

first_arg, *the_rest = ARGV

p first_arg
p the_rest
# Exercise

def git_actions
  f_arg, *r_args = ARGV
  return "Use git Action!" unless f_arg == "git"
  case r_args[0]
  when "--help"
    "Help!"
  when "commit"
    case r_args[1]
    when "-m"
      "Write a message"
    when "--help"
      "Help Commit"
    else
      "git commit <Use some flag>"
    end
  end
end

p git_actions
Made with Slides.com