0

Is there a simpler way to do this in ruby?

ops_schema_name = "ops"
tables.each do |table|
  table.schema_name = ops_schema_name
end

When reading properties, is it as simple as tables.collect(&:schema_name)? I am assuming there is a shortcut for setters.

2 Answers 2

2

You could do

schema_name_updater = -> table { table.schema_name = 'ops' }
tables.each(&schema_name_updater)
Sign up to request clarification or add additional context in comments.

2 Comments

Good example. Not simpler, but probably the simplest alternative way of doing it that there is.
&->x{ versus {|x|. It is subtle whether you can call this a shortcut.
0

Based on the good Jörg's answer, I came up with this generic solution, for any kind of objects and any number of attributes:

attrs_setter = -> obj, attrs { attrs.each { |k, v| obj.send("#{k}=", v) } }

$> tables.each { |table| attrs_setter.call(table, { :name => 'ops' }) }

$> Obj = Struct.new(:a, :b)
# => Obj
$> objs = Array.new(2) { |i| i = Obj.new('hi', 'there') }
# => [#<struct Obj a="hi", b="there">, #<struct Obj a="hi", b="there">] 
$> objs.each { |obj| attrs_setter.call(obj, { a: 'good', b: 'bye' } ) }
# => [#<struct Obj a="good", b="bye">, #<struct Obj a="good", b="bye">]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.