如何使用ruby避免重复代码块?

时间:2017-09-11 11:45:54

标签: ruby linux

我尝试在ruby脚本中转换bash脚本只是为了播放。我必须检查一个单词,这个单词将用于其他功能.bash脚本看起来像:

f_checkword(){  # Ask for user name
  unset word
  while [ -z "${word}" ]; do read -p "Enter your name ame: " word; done
  echo -e "\e[1;34m[*]\e[0m OK"
}


f_dosomethingwiththeword(){  # Function checking the name
  f_checkword  # Function asking the name of the user
  if grep -q "${Word}" "word.txt" ; then 
    echo -e "\t\e[1;32m [+] Name is OK"
  else 
    echo -e "Enter your name please"
  fi
}

我调用了f_checkword函数,然后我们就可以使用f_dosomethingwiththeword()函数了。在红宝石中,我无法做到这一点,因为这个词的价值并没有保存。

class Word
  def self.dosomeWord
    checkWord()
    puts "Name is:"
  end


  def self.dosomethingwiththeWord
    checkWord()
    puts "Name is:"
    puts "#{word}"
  end


  def self.checkWord
    puts "[*]Checking your entries..."
    File.open("word.txt").readlines.each do |word|
     puts word
     word = word.chomp
     if word.chomp.start_with?('bob', 'july', 'Smith')
       puts "[+]Name is OK"
     else
       puts "[-]ERROR: wrong name"
     end
   end
  end
end

1 个答案:

答案 0 :(得分:0)

问题解决了。我只是使用' load' checkword.rb而不是函数名称调用.Checkword定义为全局。