9、Ruby 条件执行与循环机制全解析

Ruby 条件执行与循环机制全解析

1. 赋值操作

在 Ruby 中,除了常见的赋值方式,还有一些特殊的赋值形式。例如嵌套赋值,它会先提取相应的右值,再将其赋给括号内的项,然后继续进行更高级别的赋值。

b, (c, d), e = 1,2,3,4
# 结果:b == 1, c == 2, d == nil, e == 3
b, (c, d), e = [1,2,3,4]
# 结果:b == 1, c == 2, d == nil, e == 3
b, (c, d), e = 1,[2,3],4
# 结果:b == 1, c == 2, d == 3, e == 4
b, (c, d), e = 1,[2,3,4],5
# 结果:b == 1, c == 2, d == 3, e == 5
b, (c,*d), e = 1,[2,3,4],5
# 结果:b == 1, c == 2, d == [3, 4], e == 5

另外,Ruby 也有类似其他语言的语法捷径,如 a = a + 2 可以写成 a += 2 ,这种形式内部会转换为前者。不过,Ruby 没有 C 和 Java 中的自增( ++ )和自减( -- )运算符,应使用 += 和 -= 形式。
以下是一个自定义类的示例:

class Bowdlerize
  def initial

相关推荐

9、Ruby 条件执行与循环控制全解析

本文深入解析了 Ruby 中的条件执行与循环控制机制,涵盖了赋值操作、布尔表达式、比较运算符、if/unless/case 条件语句、各种循环结构(如 while、until、for...in)、迭代器以及循环控制关键字(break、redo、next)的使用。文章还探讨了不同循环方式的适用场景、嵌套循环、范围的高级应用、代码可读性优化以及性能优化策略,并结合多个代码示例帮助开发者更好地理解和掌握 Ruby 流程控制的核心技巧。

cheese的博客 77

13、Ruby中的条件执行与循环机制

本文深入探讨了Ruby中的条件执行与循环机制,涵盖了自定义类中的运算符重载、布尔表达式的处理、布尔运算符的使用、对象比较方式、条件表达式的应用、case表达式的多路分支处理、循环结构(包括while、until、迭代器和for循环)、循环控制关键字(break、redo、next)的高级用法,以及最佳实践建议。通过丰富的代码示例和流程图,帮助开发者更好地理解和运用Ruby的流程控制功能,从而编写出更健壮、高效和易维护的代码。

e4f5g6h7的博客 51

14、Ruby 变量作用域、循环、异常处理及跳转机制详解

本文深入解析了 Ruby 中的变量作用域、循环、异常处理及跳转机制。详细介绍了不同循环结构对变量作用域的影响,以及代码块中局部变量的作用规则。在异常处理部分,涵盖了异常类的层次结构、rescue 和 ensure 的使用、系统错误处理以及自定义异常类的实现。同时,探讨了 catch 和 throw 的跳转机制,并通过实际案例展示了这些特性在复杂场景中的综合应用。最后总结了各机制的特点与应用场景,并提供了最佳实践与未来发展趋势的思考。

e4f5g6h7的博客 64

10、Ruby编程:变量作用域、循环、异常处理与模块的深入解析

本文深入解析了Ruby编程中的关键概念,包括变量作用域、循环机制、异常处理和模块的应用。详细介绍了如何利用retry和redo控制循环,如何通过rescue捕获异常并进行处理,以及模块在解决命名冲突和实现代码复用中的作用。通过实例代码和流程图,帮助开发者更好地掌握Ruby编程技巧,提高代码的健壮性和可维护性。

ruby5的博客 64

9、Ruby 编程:基础、面向对象与高级特性深度解析

本博客深入解析了 Ruby 编程语言的核心特性,涵盖基础语法、面向对象编程(消息传递、封装、继承、多态、单例类)、代码块与 Proc、混入机制等内容,并提供了实际应用场景和一个完整的图书管理系统示例。适合希望全面掌握 Ruby 语言的开发者阅读,同时也探讨了 Ruby 在 Web 开发、脚本编写和数据处理等领域的应用价值。

ll5678的博客 96

python代码爬取大众点评评论!直接copy就可以运行!

python代码爬取大众点评评论!直接copy就可以运行!

QiuQiRuQin的博客 1万+

RS-485调试踩坑实录:MAX13487数据回环问题排查与修复(附电路图)

本文深入解析了RS-485通信中MAX13487芯片的数据回环问题,提供了详细的排查过程和解决方案。通过分析芯片特性和自动换向机制,揭示了RO引脚配置不当是导致问题的关键原因,并给出硬件(添加上拉电阻)和软件(调整MCU配置)两种修复方案,附有优化设计建议和实际调试技巧。

play7的博客 1312

高性能网站设计之缓存更新的套路

看到好些人在写更新缓存数据代码时,先删除缓存,然后再更新数据库,而后续的操作会把数据再装载的缓存中。然而,这个是逻辑是错误的。试想,两个并发操作,一个是更新操作,另一个是查询操作,更新操作删除缓存后,查询操作没有命中缓存,先把老数据读出来后放到缓存中,然后更新操作更新了数据库。于是,在缓存中的数据还是老的数据,导致缓存中的数据是脏的,而且还一直这样脏下去了。 我不知道为什么这么多人用的都是这

代码技巧 1万+

从零开始:用Neo4j构建你的第一个知识图谱(附完整代码示例)

本文提供了一份从零开始的Neo4j知识图谱构建实战指南。通过一个“经典科幻电影宇宙”的具体案例,手把手教你安装环境、设计图谱模式,并使用Cypher查询语言完成节点与关系的创建、数据查询及可视化,帮助你快速掌握自下而上构建知识图谱的核心技能。

weixin_29053073的博客 478

使用 Simulink + Simscape Electrical 实现一个三相半控桥式整流器的仿真模型

本文详细介绍了使用Simulink搭建三相半控桥式整流器仿真模型的方法。主要内容包括系统结构设计、建模步骤(从创建项目到参数配置)、移相触发控制的实现,以及阻感负载下的动态响应分析。通过合理设置三相电源、整流器模块、触发控制和测量模块,实现了输出电压和电流波形的仿真观测。文章还提供了优化建议,如添加滤波器、实时控制等改进方向,为电力电子变换器的仿真研究和性能优化提供了实用指导。

amy_mhd的博客 144

AUTOSAR TcpIp模块 以太网配置开发2

someip协议之tcpIp协议

汽车电子电气 1090

【EB-03】 AUTOSAR builder与EB RTE集成

打开EB工具后,在EB的步骤是:执行MultiTask(2)-> Mapping Component to Partitions(4)->Task Mapping(5)-> SvcAs_Trigger(7)-> Code Generation(8)如涉及新增BSW Module,也需要重复以上步骤。

libuping2023的博客 975

SAP_SD模块信用管理-最早未清项判断逾期

在 SAP SD 模块的信用管理(Credit Management) 中,系统可以通过 最早未清项(Oldest Open Item) 来判断客户是否存在逾期,从而影响订单的信用检查结果。例如: 定义最大未清项目%为1%,未清天数为1天,即允许客户“逾期1天的未清应收帐款/该客户的应收帐款余额”最大比例为1%,若超过1%则将被信用冻结。的信用检查功能,用于判断客户是否有账龄过长的未清款项,并据此决定是否允许新的销售订单继续处理。然后在查看客户的信贷信息可以看到,最早的未清信息显示在系统中。

我小时候很黑的博客 881

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain&#39;s apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath(&#39;DeepLearnToolbox&#39;));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand(&#39;state&#39;,0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = &#39;sigm&#39;;%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, &#39;Too big error&#39;);```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, &#39;Too big error&#39;);```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

上一篇: 8、Ruby 方法与表达式全解析
下一篇: 10、Ruby编程:变量作用域、循环、异常处理与模块的深入解析
ruby5
博客等级 码龄15年 29粉丝 893原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址