ruby 中的静态变量,就像在 C 函数中一样

编程入门 行业动态 更新时间:2024-10-12 05:51:22
本文介绍了ruby 中的静态变量,就像在 C 函数中一样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

Ruby 中是否有静态变量之类的东西会像在 C 函数中一样?

Is there any such thing as static variables in Ruby that would behave like they do in C functions?

这是我的意思的一个简单示例.它将6\n7\n"打印到控制台.

Here's a quick example of what I mean. It prints "6\n7\n" to the console.

#include <stdio.h> int test() { static int a = 5; a++; return a; } int main() { printf("%d\n", test()); printf("%d\n", test()); return 0; }

推荐答案

在方法中作用域变量并返回 lambda

Scope your variable in a method and return lambda

def counter count = 0 lambda{count = count+1} end test = counter test[] #=>1 test[] #=>2

更多推荐

ruby 中的静态变量,就像在 C 函数中一样

本文发布于:2023-10-10 17:41:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1479290.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:就像   变量   静态   函数   ruby

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!