I am a .NET developer and recently started learning ruby with ruby_koans. Some of Ruby’s syntaxes are amazing and one of them is the way it handles “Sandwich” code.
The following is ruby sandwich code.
def file_sandwich(file_name)
file = open(file_name)
yield(file)
ensure
file.close if file
end
def count_lines2(file_name)
file_sandwich(file_name) do |file|
count = 0
while line = file.gets
count += 1
end
count
end
end
def test_counting_lines2
assert_equal 4, count_lines2("example_file.txt")
end
I am fascinated that I can get rid of the cumbersome “file open and close code” each time I access a file but cannot think of any C# equivalent code. Maybe, I can use IoC’s dynamic proxy to do the same thing, but is there any way I can do it purely with C#?
Many thanks in advance.
You certainly don’t need anything IoC-related here. How about:
In this case it doesn’t help very much, as the
usingstatement already does most of what you want… but the general principle holds. Indeed, that’s how LINQ is so flexible. If you haven’t looked at LINQ yet, I strongly recommend that you do.Here’s the act
CountLinesmethod I’d use:Note that this will still only read a line at a time… but the
Countextension method acts on the returned sequence.In .NET 3.5 it would be:
… still pretty simple.