具有特定格式的Array to String

时间:2015-09-16 18:02:38

标签: arrays ruby string format

我有这样的哈希:

@password_constraints = {
  length: 'Must be at least 6 character long.',
  contain: [
      'one number',
      'one lowercase letter',
      'one uppercase letter.'
  ]
}

我想写一个方法,返回一个由这个哈希构建的人类可读字符串,如下所示:

  

长度必须至少为6个字符。必须包含:一个数字,一个小写字母一个大写字母。

目前,我有一个非常详细的方法each迭代@password_constraints[:contain]数组,并有几个条件来检查我是否必须放,或{{ 1}}或者没有。

但我想要与and几乎相同的行为,但最后一个分隔符必须是join(', ')

我正在寻找某种具有特殊and的解决方案:

join

有没有办法让它更紧凑或类似Ruby?

3 个答案:

答案 0 :(得分:4)

您可以使用splat运算符拆分数组,只检查一个字符串是否只有一个字符串:

def message(constraints)
  *others, second_last, last = constraints[:contain]
  second_last += " and #{last}" unless last.nil?
  "#{constraints[:length]} Must contain: #{(others << second_last).join(', ')}"
end

@password_constraints = {
  length: 'Must be at least 6 character long.',
  contain: [
      'one number',
      'one lowercase letter',
      'one uppercase letter.'
  ]
}

message(@password_constraints)
# => "Must be at least 6 character long. Must contain: one number, one lowercase letter and one uppercase letter." 

# if @password_constraints[:contain] = ['one lowercase letter', 'one uppercase letter.']
message(@password_constraints)
# => "Must be at least 6 character long. Must contain: one lowercase letter and one uppercase letter." 

# if @password_constraints[:contain] = ['one lowercase letter']
message(@password_constraints)
# => "Must be at least 6 character long. Must contain: one lowercase letter"

答案 1 :(得分:0)

我会在这里使用一个猴子补丁来简洁(是的,我的join_requirements方法可能看起来更好一些)。

class Array
  def join_requirements
    result = ""
    self.each do |requirement|
      if requirement == self.last
        result << "and " << requirement
      else
        result << requirement + ", "
      end
    end
    result
  end
end

然后在你的代码中你会看到:

contain = ['one number','one lowercase letter','one uppercase letter.']
puts contain.join_requirements
# => one number, one lowercase letter, and one uppercase letter.

答案 2 :(得分:-1)

Here是Ruby中一个有趣的小速手技巧,你可以用数组来减少对冗长join的需求。

def password_constraints
  @password_constraints[:length] << ' Must contain.' << @password_constraints[:contain] * ", "
end

Array类'*运算符显式检查string第二个操作数,然后转换为调用join