Skip to content

Instantly share code, notes, and snippets.

@kell05
Created June 18, 2012 22:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kell05/2951300 to your computer and use it in GitHub Desktop.
Save kell05/2951300 to your computer and use it in GitHub Desktop.
Blocks
# Example 1
def file_read(filename)
file = File.new(filename,'r')
yield file # file is the variable passed into the block (anything between do and end is a block) f is the variable used the access this in example 1 usage.
file.close
end
# Example 1 usage
file_read('temp.rb') do |f| # f is the file descriptor for accessing methods on the file
puts f.read # reads the whole file as a string puts is essentially println in java
end # File Closes here
# Example 2
File.open('temp.rb','r') do |f|
puts f.read
end
# Example 1 is my remake of Example 2 which is part of the ruby lang.
# The regex
puts data.gsub(/(.+)\n/){$1+"\t") # This subs all the lines with one or more chars(non empty lines) the {} takes the line and appends a tab
# Not the lines between the records don't get changed as they have zero characters before the new line.
# This is a classic technique in regex to use matching groups. $1 signifies the first matching group.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment