Skip to content

Instantly share code, notes, and snippets.

@muhammadyana
Created June 9, 2017 08:55
Show Gist options
  • Save muhammadyana/d580db76928261fc5334f90577a9ccee to your computer and use it in GitHub Desktop.
Save muhammadyana/d580db76928261fc5334f90577a9ccee to your computer and use it in GitHub Desktop.
Read, write update and delete file in Ruby
#thursday-08-2017
#@41studio
#Muhammad Yana Mulyana
#R/W File in ruby
File.open("sample.txt", "r") do |f|
f.each_line do |line|
puts line
end
end
File.new("yana.txt", "w")
# read file
word_list = File.open("sample.txt")
word_in_error = catch(:done) do
result = []
while line = word_list.gets
word = line.chomp
throw(:done, word) unless word =~ /^\w+$/
result << word
end
puts result.reverse
end
if word_in_error
puts "Failed: '#{word_in_error}' found, but a word was expected"
end
another way search word or character in file
File.open("sample.txt") do
|file|
file.each_line("e"){
|line|
puts "Got #{line.dump}"
}
end
#simple way to read file in ruby
#
IO.foreach("sample.txt"){
|line|
puts line
}
#read count char in file
str = IO.read("sample.txt")
puts str.length
#read into array
arr = IO.readlines("sample.txt")
puts arr.length
puts arr[0]
#Write into file
puts "Enter text "
char = gets()
File.open("sample.txt", "w") do
|file|
a = file.puts char
#puts a.true?
unless a
puts "Write file success"
else
puts "Faile write file"
end
end
require "stringio"
ip = StringIO.new("Now is\nthe time\nto learn\nRuby!")
op = StringIO.new("sample.txt", "w")
ip.each_line do
|line|
op.puts line.reverse
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment