You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby中如何在方法内调用另一个方法?密码生成器调用失效求解

问题1:Ruby字符串插值语法错误

你写的puts %(Password 1: {generate_password})没有使用正确的插值语法,Ruby中要在字符串内执行表达式并插入结果,需要在大括号前加#,正确写法是puts %(Password 1: #{generate_password}),你当前的写法会把{generate_password}当作普通文本直接输出,不会调用方法。

问题2:apply_map方法定义位置错误

你现在把apply_map方法定义在了Challenge类的外部,属于全局方法,类内部的generate_password调用这个方法时,全局方法无法访问到Challenge类的实例变量@prng、@map,也无法访问类常量KEY,会直接报错或者返回异常结果,需要把这个方法的定义移到Challenge类内部的私有方法区域。


修正后的完整代码

require 'digest'

class Challenge
  KEY = [
    '4', '5', '6', '7',
    '8', '9', 'A', 'B',
    'C', 'D', 'E', 'F',
    '0', '1', '2', '3'
  ]

  def initialize(email)
    @email = email # && raise
    puts 'This object was initialized!'
  end

  def print_password
    puts %(Password 1: #{generate_password}) # 修正插值语法
  end

  private

  def generate_password
    @hash = Digest::SHA1.hexdigest(@email)
    @id = @hash.scan(/\d+/).map(&:to_i).inject(:+)
    @prng = Random.new(@id)

    prepare_map
    apply_map
  end

  def prepare_map
    @map      = []
    id_string = @id.to_s
    id_size   = id_string.size

    map_string = id_string * (KEY.size.to_f / id_size).ceil

    0.upto(15) do |i|
      @map[i] = map_string[i].to_i
    end

    @map
  end
  
  # apply_map移到类内部私有区域
  def apply_map
    calculated_key = KEY.shuffle(random: @prng).map.with_index do |char, i|
      (char.bytes[0] + @map[i]).chr
    end

    calculated_key.join
  end
end

me = Challenge.new('me@gmail.com') # 初始化新对象
me.print_password # 正常输出计算后的密码

内容的提问来源于stack exchange,提问作者Renārs Abeļūns

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 15:18:01