我去了http://ruby-doc.org/core/classes/Array.html#M002198并且无法找出采用一系列名称的方法,例如
people = [chris,george,jerry,bob,bill,julie,josh]
我希望能够让用户选择一个字母“b”然后按Enter键并提取所有带有第一个字母'b'的元素并将它们放在一个单独的数组中。在这种情况下,它将[bob,bill] .slice命令应该适用于此但我不知道如何告诉它只看元素的第一个字母?这会是某种需要像people.slice()
那样填充的论点吗?people_selector = gets.chomp.to_s
people.slice(people_selector)
print people
不幸的是,谷歌也没有帮助。发布代码,所以我可以查看参数值。
答案 0 :(得分:9)
您可能需要select
,而不是slice
:
$ irb
>> people = ["chris", "bob", "bill", "julie"]
=> ["chris", "bob", "bill", "julie"]
>> letter = gets.chomp.downcase
B
=> "b"
>> people.select { |person| person[0,1] == letter }
=> ["bob", "bill"]
此外,无需将to_s
添加到gets.chomp
;你应该已经有了一个字符串。
在Ruby 1.9中,您可以改为:
>> people.select { |person| person[0] == letter }
=> ["bob", "bill"]
在Ruby 1.9中,索引到字符串总是返回一个字符串;在早期版本中,使用单个值索引到字符串中会获得一个字符。另一个应该适用于所有版本的替代方案是:
>> people.select { |person| person[0] == letter[0] }
=> ["bob", "bill"]
答案 1 :(得分:3)
如果要从原始数组中删除元素并将它们放入新数组中,请查看分区
>> people = "chris,george,jerry,bob,bill,julie,josh".split(",")
=> ["chris", "george", "jerry", "bob", "bill", "julie", "josh"]
>> bs, people = people.partition {|name| name[0,1] == 'b'}
=> [["bob", "bill"], ["chris", "george", "jerry", "julie", "josh"]]
>> bs
=> ["bob", "bill"]
>> people
=> ["chris", "george", "jerry", "julie", "josh"]
答案 2 :(得分:1)
简短的回答是你可以使用select:
people.select {|person| person[0,1] == letter}
这是一个示例实现。首先,我们有一个单元测试,描述了需要发生的事情:
class PeopleListTest < Test::Unit::TestCase
def setup
@people = PeopleList.new "jack", "jill", "bruce", "billy"
end
def test_starting_with
assert_equal ["bruce", "billy"], @people.starting_with("b")
assert_equal ["jack", "jill"], @people.starting_with("j")
assert_equal [], @people.starting_with("q")
end
end
如果您正在尝试这样做,那么进行该传递的代码是:
class PeopleList
def initialize *people
@people = people
end
def starting_with letter
return @people.select {|person| person[0,1] == letter}
end
end
我希望这会有所帮助。祝你好运。
答案 3 :(得分:1)
这也有效,虽然效率略低于Brian,但更灵活。
>> a = ['bob', 'abe', 'fred', 'bill']
=> ["bob", "abe", "fred", "bill"]
>> a.select{|s| s =~ /^b/}
=> ["bob", "bill"]
答案 4 :(得分:0)
你将获得比收集更多的里程数