Created
June 18, 2012 22:57
-
-
Save kell05/2951300 to your computer and use it in GitHub Desktop.
Blocks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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