Pass an optional argument from parent to child in Ruby

There should be a DRY way to do this without two separate calls to File.open and without the visible default File.open value for permissions . Right?

 def ensure_file(path, contents, permissions=nil) if permissions.nil? File.open(path, 'w') do |f| f.puts(contents) end else File.open(path, 'w', permissions) do |f| f.puts(contents) end end end 
+4
source share
2 answers

Using splat (i.e. *some_array ) will work in the general case:

 def ensure_file(path, contents, permissions=nil) # Build you array: extra_args = [] extra_args << permissions if permissions # Use it: File.open(path, 'w', *extra_args) do |f| f.puts(contents) end end 

In this case, you already get permissions as a parameter, so you can simplify this (and make it even more general) by resolving any number of optional arguments and passing them:

 def ensure_file(path, contents, *extra_args) File.open(path, 'w', *extra_args) do |f| f.puts(contents) end end 

The only difference is that if too many arguments are passed, an ArgumentError will be raised when File.open called instead of ensure_file .

+4
source
 File.open(path, 'w') do |f| f.puts(contents) f.chmod(permission) if permission end 
+1
source

Source: https://habr.com/ru/post/1386567/


All Articles