B
B
Bogdan2017-07-31 11:53:39
Ruby on Rails
Bogdan, 2017-07-31 11:53:39

Add quotes for string variable?

Hello. The change has hash { tstr: 'sssss', tnbr: 10, tdate: Date.today } and you need to wrap strings and dates in quotes. What would the output be "tstr = 'sssss',tnbr = 10,tdate = '2017-07-31'" It
seems to work, but maybe there is a better solution? Thank you.

data = { tstr: 'sssss', tnbr: 10, tdate: Date.today }
puts data.map{ |k, v| "#{k} = #{ ['String', 'Date' ].include?( v.class.name ) ? "'#{ v }'" : v }" }.join( ',' )

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Blokhin, 2017-12-18
@TITnet

Bogdan , in general, your solution is working.
But I would not recommend you to get involved in "one-liners".

# encoding: utf-8
# @see https://toster.ru/q/447239

require 'date'

# @param [Hash] source
# @return [String]
def main(source, equal = ' = ', separator = ', ', result = [])
  source.map do |key, value|
    case value
    when String, Date
      value = %Q('#{value}')
    when Fixnum, Bignum, Float
    else
      raise "Wrong class for #{value}"
    end
    result << "#{key}#{equal}#{value}"
  end

  result.join separator
end

# passed
# tstr='foo',tnbr=42,tdate='2017-12-18'
source = { tstr: 'foo', tnbr: 42, tdate: Date.today }
puts main source, '=', ','

# passed
# tstr = 'foo', tnbr = 42.42, tdate = '2017-12-18'
source = { tstr: 'foo', tnbr: 42.42, tdate: Date.today }
puts main source

# failed
source = { tstr: %w(foo), tnbr: 42, tdate: Date.today }
puts main source

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question