Ruby Struct:用空格替换nil值

时间:2017-03-14 14:34:05

标签: ruby

我需要确保在Struct内部没有nil或空值,当nil我想用空格替换它时,但以下内容不起作用。

这可能吗?怎么样?感谢..

s = Struct.new(:datum, :string1, :string2, :string3, :nummer)
r = s.new(Time.now(), "", "test", nil, 0.0)

p r

r.each do |a|
    a.replace(" ") if a.class == String && a.empty?
    a = " " if a.nil?
end

p r

之前:

#<struct datum=2017-03-14 15:28:40 +0100, string1="", string2="test", string3=nil, nummer=0.0>

后:

#<struct datum=2017-03-14 15:28:40 +0100, string1=" ", string2="test", string3=nil, nummer=0.0>

想:

#<struct datum=2017-03-14 15:28:40 +0100, string1=" ", string2="test", string3=" ", nummer=0.0>

3 个答案:

答案 0 :(得分:3)

r.members.each do |m|
  r.public_send("#{m}=", " ") if r.public_send(m).to_s.empty?
end

答案 1 :(得分:3)

您可以将Struct与块一起使用,并使用默认值覆盖读者:

s = Struct.new(:datum, :string1, :string2, :string3, :nummer) do
  BLANK = " ".freeze
  def datum
    return BLANK if nil_or_empty?(values[0])
    values[0]
  end

  def string1
    return BLANK if nil_or_empty?(values[1])
    values[1]
  end

  def string2
    return BLANK if nil_or_empty?(values[2])
    values[2]
  end

  def string3
    return BLANK if nil_or_empty?(values[3])
    values[3]
  end

  def nummer
    return BLANK if nil_or_empty?(values[4])
    values[4]
  end

  def nil_or_empty?(val)
    val.nil? || val.empty?
  end
end



r = s.new(Time.now(), "", "test", nil, 0.0)
p r.string3
p r.string1

输出:

" "
" "

答案 2 :(得分:1)

使@Anthony的答案更加健壮:

s = Struct.new(:datum, :string1, :string2, :string3, :nummer) do
  BLANK = " ".freeze
  members.each_with_index do |m, idx|
    define_method m do
      self.[]=(idx, BLANK.dup) if values[idx].to_s.empty?
      values[idx]
    end
  end
end

r = s.new(Time.now(), "", "test", nil, 0.0)
p r.string3
#⇒ " "
p r.string1
#⇒ " "