弄清楚Ruby的字符串

时间:2015-09-11 19:22:35

标签: ruby

class Person
    def initialize(name)
        set_name(name)
    end
    def name
        @first_name + ' ' + @last_name
    end
    private
    def set_name(name)
        first_name, last_name = name.split(/\s+/)
        set_first_name(first_name)
        set_last_name(last_name)
    end
    def set_first_name(name)
        @first_name = name
    end
    def set_last_name(name)
        @last_name = name
    end
end
male_names = %w{George Emmanuel Bruno Connel  Cletus Samuel}
female_names = %w{Joy Stella Patience Rita Rachael Ruth Elizabeth}
puts "Please input your two names:"
    n = gets
    p = Person.new(n)
    full_name = n.scan(/\w+/)
    names = full_name.select do |name|
        if male_names.include?(name)
            nn=name
            na = "Mr "+nn
            puts "Welcome #{na}"
        elsif female_names.include?(name)
            na = "Ms "+name
            puts "Welcome #{na}"
        else puts "name not found!\nAre you sure you exist?"
        end
    end

如果我输入Connel Samuel,则会打印:

  

欢迎康纳尔先生   欢迎塞缪尔先生

我只是想打印出来:

  

欢迎Connel Samuel先生。

1 个答案:

答案 0 :(得分:1)

这里的整个Person课程都是红鲱鱼。你没有在最后的印刷品中使用它。你刚刚用过

n.scan(/\w+/)

并查看从输入中获得的单词。有两个词 - ConnelSamuel,每个词都会得到自己的迭代。因此Welcome Mr Connel Welcome Mr Samuel

<小时/> 要修复它,您可以检查第一个或第二个名字是否在男/女名单中并打印该人的姓名:

if p.name.split.find { |name| male_names.include?(name) }
  puts "Welcome Mr #{p.name}"
elsif p.name.split.find { |name| female_names.include?(name) }
  puts "Welcome Ms #{p.name}"
else
  puts "name not found!\nAre you sure you exist?"
end