[英]Check for a string and print the first word in the matched line in Ruby
我想检查文件中是否存在字符串,如果存在,请打印匹配行的第一个单词。
sample.txt
id = class\234ha, class\poi23, class\opiuj, cap\7y6t5
dept = sub\6985de, ret\oiu87, class\234ha
如果是class \\ 234ha字符串,则应打印:id和dept。
我知道如何使用检查字符串是否存在
File.open('sample.txt').grep(/class\\234ha/)
但不确定如何打印匹配行的第一个单词。 尝试使用.first方法,但没有运气。
请在这里任何帮助。 谢谢。
像这样吗
File.open('sample.txt').grep(/class\\234ha/) { |line| line.split.first }
=> ["id", "dept"]
您可以将一个块传递给grep
方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.