Tell me how to create a similar hash. I have a view loop:

sms_send = {} SmsSend.all.each do |record| if !record.is_send sms_send.merge!(record.sms_number => Russian.translit(record.sms_text)) record.is_send = 1 record.save end 

At the output, the hash now looks like this: {'12345678' => 'test1', '123456789' => 'test1'} , and how to make another value added there, record.uid , so that the output has the following hash:

 { 'record.uid(1)' => { record.sms_number(1) => Russian.translit(record.sms_text(1)) }, 'record.uid(2)' => { record.sms_number(2) => Russian.translit(record.sms_text(2)) } } 

Ie, that at first there was a unique key record.uid , and then went the values? That at each iteration there values ​​were added, depending on a condition.

    1 answer 1

    If the uid is unique, you can use the following structure:

     sms_end = {} SmsSend.find_each.with_object(sms_end) do |record, memo| next if record.is_send memo[record.uid] = {record.sms_number => Russian.translit(record.sms_text)} end 

    The result will be saved in sms_end .

    As suggested in the comments, this is the best option.

    • And you can ask, what has become worse readability? :) By using a variable a little further than from the current scope, what was previously covered by each_with_object ? So you can do .find_each.with_object(sms_send) . - D-side
    • @ D-side, well, I'm not sure that it became worse. I just try to avoid in variables, where possible, variables from outside. About with_object , to my shame, did not know. So the truth turns out neater. Thank. The only minus is the methods of chaining. But, in any case, it is at least as good as the first option. - anoam