Why is “slurping” a file not a good practice?

Again and again we see questions asking about reading a text file to process it line-by-line, that use variations of read, or readlines, which pull the entire file into memory in one action. The documentation for read says: Opens the file, optionally seeks to the given offset, then returns length bytes (defaulting to the rest … Read more

How to dynamically create a local variable?

You cannot dynamically create local variables in Ruby 1.9+ (you could in Ruby 1.8 via eval): eval ‘foo = “bar”‘ foo # NameError: undefined local variable or method `foo’ for main:Object They can be used within the eval-ed code itself, though: eval ‘foo = “bar”; foo + “baz”‘ #=> “barbaz” Ruby 2.1 added local_variable_set, but … Read more

When monkey patching an instance method, can you call the overridden method from the new implementation?

EDIT: It has been 9 years since I originally wrote this answer, and it deserves some cosmetic surgery to keep it current. You can see the last version before the edit here. You can’t call the overwritten method by name or keyword. That’s one of the many reasons why monkey patching should be avoided and … Read more

Ruby ampersand colon shortcut [duplicate]

Your question is wrong, so to speak. What’s happening here isn’t “ampersand and colon”, it’s “ampersand and object”. The colon in this case is for the symbol. So, there’s & and there’s :foo. The & calls to_proc on the object, and passes it as a block to the method. In Ruby, to_proc is implemented on … Read more

Why do Ruby setters need “self.” qualification within the class?

Because otherwise it would be impossible to set local variables at all inside of methods. variable = some_value is ambiguous. For example: class ExampleClass attr_reader :last_set def method_missing(name, *args) if name.to_s =~ /=$/ @last_set = args.first else super end end def some_method some_variable = 5 # Set a local variable? Or call method_missing? puts some_variable … Read more