Project1

标题: 这是我代码写错了还是? [打印本页]

作者: SailCat    时间: 2017-12-2 23:28
标题: 这是我代码写错了还是?
不想连写20条重复的内容,想把1简化成2,结果死活通不过……

是xp ruby版本太低了还是我写错了……

RUBY 代码复制
  1. #==============================================================================[/font]
  2. [font=&quot]# ■ Vocab[/font]
  3. [font=&quot]#------------------------------------------------------------------------------[/font]
  4. [font=&quot]# 所有用语的整合模块。[/font]
  5. [font=&quot]#==============================================================================[/font]
  6. [font=&quot]module Vocab[/font]
  7. [font=&quot]#--------------------------------------------------------------------------[/font]
  8. [font=&quot]# ● 导入已经在数据库里定义的术语[/font]
  9. [font=&quot]#--------------------------------------------------------------------------[/font]
  10. [font=&quot]def self.gold; $data_system.words.gold; end[/font]
  11. def self.hp; $data_system.words.hp; end
  12. def self.sp; $data_system.words.sp; end
  13. ....
  14. [font=&quot]end


RUBY 代码复制
  1. #==============================================================================
  2. # ■ Vocab
  3. #------------------------------------------------------------------------------
  4. #   所有用语的整合模块。
  5. #==============================================================================
  6. module Vocab
  7.   #--------------------------------------------------------------------------
  8.   # ● 导入已经在数据库里定义的术语
  9.   #--------------------------------------------------------------------------
  10.   def self.words(sym);    $data_system.words.send(sym);                   end
  11.   [:gold, :hp, :sp, :str, :dex, :agi, :int, :atk, :pdef, :mdef,
  12.     :weapon, :armor1, :armor2, :armor3, :armor4,
  13.     :attack, :skill, :defend, :item, :equip].each do |sym|
  14.     self.send :define_method, sym {words(sym)}
  15.   end
  16. end


作者: chd114    时间: 2017-12-2 23:48
本帖最后由 chd114 于 2017-12-2 23:49 编辑
  1. %w(gold hp mp str dex).each do |type| eval %{
  2. def self.#{type}; $data_system.words.#{type};}end
复制代码

这样如何···
作者: SixRC    时间: 2017-12-3 00:56
本帖最后由 SixRC 于 2017-12-3 01:02 编辑

十四行 {} 改成 do ... end 就可以的
或者用括号把 sym 括起来
原因应该是 方法的优先度高于变量..不加括号解释器认为 sym 是方法

作者: RaidenInfinity    时间: 2017-12-3 01:07
本帖最后由 RaidenInfinity 于 2017-12-3 01:08 编辑

以下代码于Steam正版RMXP空工程内测试可用(包括实际调用):
RUBY 代码复制
  1. module Vocab
  2.   class << self
  3.     WORD_SYM =   [:gold, :hp, :sp, :str, :dex, :agi, :int, :atk, :pdef, :mdef,
  4.                   :weapon, :armor1, :armor2, :armor3, :armor4,
  5.                   :attack, :skill, :guard, :item, :equip]
  6.  
  7.     WORD_SYM.each do |sym|
  8.       target = RPG::System::Words.instance_method(sym)
  9.       define_method(sym) do
  10.         target.bind($data_system.words).call
  11.       end
  12.     end  
  13.   end  
  14. end





欢迎光临 Project1 (https://rpg.blue/) Powered by Discuz! X3.1