rubyruby-2.0ruby-3

remove last character from looping Hash


can you help me to solve this problem with this code?

total_user_input = []

while true
  print "Field Name: "
  user_input = gets.chomp
  break if user_input.empty?
  total_user_input << user_input
end


total_user_input.each do |input|
  aa = input.split(":").reduce {|first, second| "  \t'#{first}': '#{second}',\r\n".gsub("'",'"') }
  puts aa.chomp(',')
end

and the result I get

"name": "string",
"desc": "string",
"price": "integer",

but what I want is just remove the last comma only

"name": "string",
"desc": "string",
"price": "integer"

thank you for helping me


Solution

  • I don't know actualy what your scenario But I base on your expected and You can try it.

    total_user_input = [
      "name:test",
      "age:30"
    ]
    
    input_length = total_user_input.size
    total_user_input.each_with_index do |input, index|
      aa = input.split(":").reduce {|first, second| "  \t'#{first}': '#{second}',\r\n".gsub("'",'"') }
      aa = aa.gsub(',', '') if index == input_length - 1 # or aa.slice(-1)
      puts aa
    end
    

    => My result

    "name": "test",
    "age": "30"