Skip to content

Instantly share code, notes, and snippets.

@dminuoso

dminuoso/ex.md Secret

Last active March 6, 2018 13:19
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 dminuoso/198d794f2b4f6bfdf63a0ec0615d6f59 to your computer and use it in GitHub Desktop.
Save dminuoso/198d794f2b4f6bfdf63a0ec0615d6f59 to your computer and use it in GitHub Desktop.

File.open("foo.csv", "w") { |fh| fh.puts "Hello world" }

File.open takes 3 arguments.

  1. A string for the filename: "foo.csv"
  2. A string for the mode: "w"
  3. A function taking one argument, named "fh"

This syntax would have been more honest looking like this:

File.open("foo.csv", "w", -> { |fh| fh.puts "Hello world" })

Or using separate variables:

handler = -> { |fh| fh.puts "Hello world" }
filename = "foo.csv"
mode = "w"

File.open(filename, mode, handler)

Ruby does let you do this kind of, if you use an annoying little & in there.

handler = -> { |fh| fh.puts "Hello world" }
filename = "foo.csv"
mode = "w"

File.open(filename, mode, &handler)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment