Skip to content

Instantly share code, notes, and snippets.

@gouf
Created September 22, 2019 11:38
Show Gist options
  • Save gouf/3471f5dfb96667110fa46ca5eebdf21f to your computer and use it in GitHub Desktop.
Save gouf/3471f5dfb96667110fa46ca5eebdf21f to your computer and use it in GitHub Desktop.
[Ruby - saveする前の値の加工|teratail](https://teratail.com/questions/213240)
# frozen_string_literal: true
def reassign_order_index(hash)
keys = hash.keys
values = hash.values
reordered_values =
values.map.with_index(1) { |x, i| x.update('order' => i) }
keys.zip(reordered_values).to_h
end
# 処理前
params = {
'utf8' => '✓',
'authenticity_token' =>
'F98xi8sKXsi7vZmlhtGZpTXpMU0DsDv4FexHYHzVRgXpbkoiJF5429GL1+IIPGZMIo',
'hoge' =>
{ '0' => { 'title' => 'title1', 'order' => '1' },
'1' => { 'name' => 'title2', 'order' => '1' } },
'fuga' =>
{ '0' => { 'name' => 'name', 'order' => '1' },
'1' => { 'name' => 'title2', 'order' => '1' } },
'commit' => '登録'
}
hoge = reassign_order_index(params.dig('hoge'))
fuga = reassign_order_index(params.dig('fuga'))
params.update('hoge' => hoge)
params.update('fuga' => fuga)
# 処理後
pp params
# =>
# {"utf8"=>"✓",
# "authenticity_token"=>
# "F98xi8sKXsi7vZmlhtGZpTXpMU0DsDv4FexHYHzVRgXpbkoiJF5429GL1+IIPGZMIo",
# "hoge"=>
# {"0"=>{"title"=>"title1", "order"=>1}, "1"=>{"name"=>"title2", "order"=>2}},
# "fuga"=>
# {"0"=>{"name"=>"name", "order"=>1}, "1"=>{"name"=>"title2", "order"=>2}},
# "commit"=>"登録"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment