Ruby中如何通过动态method参数创建并调用变量名称的方法?

2026-04-11 19:511阅读0评论SEO基础
  • 内容介绍
  • 相关推荐

本文共计218个文字,预计阅读时间需要1分钟。

Ruby中如何通过动态method参数创建并调用变量名称的方法?

在Python中,你可以使用下划线作为对象的实例变量名,但通常推荐使用一个双下划线前缀(例如`__myvar`),这样做可以避免与Python的内置属性和方法冲突。以下是对您提供的代码的简化修改:

pythonclass MyClass: def __init__(self, ex, ey): self.__myvar=ex self.__myothervar=ey

def test(self, element): return isinstance(element, MyClass)

我如何使用参数值作为对象的实例变量名?

这是对象

Class MyClass def initialize(ex,ey) @myvar = ex @myothervar = ey end end

我有以下方法

def test(element) instanceofMyClass.element #this obviously doesnt work end

如何让test方法返回myvar或myothervar值,具体取决于element参数.我不想写if条件,但是如果可能的话,我想通过元素将myvar或myother var传递给对象实例.

def test(element) instanceofMyClass.send(element.to_sym) end

如果instanceofMyClass没有响应元素,则会丢失方法错误.

Ruby中如何通过动态method参数创建并调用变量名称的方法?

本文共计218个文字,预计阅读时间需要1分钟。

Ruby中如何通过动态method参数创建并调用变量名称的方法?

在Python中,你可以使用下划线作为对象的实例变量名,但通常推荐使用一个双下划线前缀(例如`__myvar`),这样做可以避免与Python的内置属性和方法冲突。以下是对您提供的代码的简化修改:

pythonclass MyClass: def __init__(self, ex, ey): self.__myvar=ex self.__myothervar=ey

def test(self, element): return isinstance(element, MyClass)

我如何使用参数值作为对象的实例变量名?

这是对象

Class MyClass def initialize(ex,ey) @myvar = ex @myothervar = ey end end

我有以下方法

def test(element) instanceofMyClass.element #this obviously doesnt work end

如何让test方法返回myvar或myothervar值,具体取决于element参数.我不想写if条件,但是如果可能的话,我想通过元素将myvar或myother var传递给对象实例.

def test(element) instanceofMyClass.send(element.to_sym) end

如果instanceofMyClass没有响应元素,则会丢失方法错误.

Ruby中如何通过动态method参数创建并调用变量名称的方法?