Programming Ruby (Part I. Facets of Ruby)

本文介绍了Ruby编程语言的基础知识,包括安装配置、数据类型如字符串、数组和哈希的使用方法,控制结构、正则表达式及文件读写等内容,并探讨了类、对象、变量的概念以及访问控制机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Getting Start

 

OS X Distributions

1, MacPorts: package management system

 

$ sudo port install ruby19
 

2, Building ruby from source, get source and do follow:

./configure
make
make test 
make install
 

Check which shell has been using, do follow:

 

echo $SHELL

 

if console display bin/bash , we should change inside of ~/.profile or ~/.bash_profile .

 

export PATH=/<path>:$PATH

 

/<path> :   => the path which you want to add into environment variable and use,  : to separate each path
$PATH        => previous paths which already have been added into

 

 

 

Ruby.new

 

1, Ruby is an Object-Oriented Language

 

The most common String object is to use string literals, which are sequences of characters between single or double quotation marks. The difference between the two forms is the amount of processing ruby does on the string while constructing the literal.

 

in single-quoted case, Ruby does very little.

 

in double-quoted case, Ruby does more work.
 i) it looks for substitutions (for example, " \n " => newline)
 ii) expression interpolation  (for example, "Good night, #{name} ")

 

The value returned by a Ruby method is the value of the last expression evaluated, so we can get rid of the temporary variable and return statement altogether.

 

Ruby uses a convention : the first characters of a name indicate how the name is used.
 i). Local variables, method parameters, and method names should all start with a lowercase or with an underscore.
 ii). Global variables are prefixed with a dollar sign($ ) and instance variables begin with an at sign(@ )
 iii). Class variables start with two at signs (@@ )
 iv). Class names, module names and constants must start with an uppercase letter.

 

2, Arrays and Hashes

 

arrays and hashes are indexed collections. with arrays, the key is an integer, whereas hashes support any object as a key.

in Ruby, nil is an object.

 

simple way to create array (for example : a = %w{ cat dog bee } same as a = [ 'cat', 'dog', 'bee' ]

 

Hash use braces rather than square brackets, and the literal must supply two objects for every entry: one for the key, the other for the value.

 

inst_section = { 
  'cello'    =>   'string',
  'drum'   =>   'percussion'
}

 

 

3, Symbols

 

Symbols are simply constant names that you don't have to pre declare and that are guaranteed to be unique. (for example :symbol_name )

symbols are so frequently used as hash keys in Ruby 1.9, you can use name : value pairs to create a hash if the keys are symbols.

inst_section = {
  :cello => 'string',
  :drum => 'percussion'
}

    在ruby 1.9里面, 可以不加:, 直接 cello => 'string'

 

 

4, Control Structures

 

Most statements in Ruby return a value, which means you can use them as conditions.

Ruby statement modifiers are a useful shortcut if the body of an if or while statement is just a single expression. Simply write the expression, followed by if or while and the condition.

 

for example:

 

  if radiation > 3000
    puts "Danger, Will Robinson"
  end 

  puts "Danger, Will Robinson" if radiation > 3000
 

 

5, Regular Expressions

 

 

 

 

6, Blocks and Iterators

 

code blocks, which are chunks of code you can associate with method invocations, almost as if they were parameters.

{ } for single-line

do / end for multi-line

A method can then invoke an associated block one or more times using the Ruby yield statement. You can think of yield as being someting like a method call that invokes the block associated with the call to the method containing the yield.

 

You can provide arguments to the call to yield, and they will be passed to the block. Within the block, you list the names of the parameters to receive these arguments between vertical bars (| params |).

 

Code blcoks are used throughout the Ruby library to implement iterators.

 

 

7, Reading and 'Riting

 

puts writes its arguments with a newline after each; print also writes its arguments but with no newline. Both can be used to write to any I/O object, but by default they write to standard output.


printf , which prints its arguments under the control of a format string (just like printf in C or Perl)
printf : 对string的格式进行控制

 

 

8, Command-Line Arguments

the array ARGV contains each of the arguments passed to the running program.

 

 

 

Classes, Objects, and Variables

 

 

1, Objects and Attributes

 

Writing accessor methods is such a common idiom, Ruby provides a convenient shortcut. attr_reader creates these atrribute reader methods.

attr_reader :isbn, :price
 

you can think of :isbn as meaning the name isbn and plain isbn as meaning the value of the variable.

 

 

Virtual Attributes

 

2, Classes Working with Other Classes

 

require_relative because the location of the file we’re loading is relative to the file we’re loading it from (same directory)

 

CSV (Comma-separated Values) file is a simple text format for a database table.

CSV file format: "ISBN","14.99"   Note: there is NO space between comma.

 

 

3, Access Control

Ruby gives three levels of protection:

 i). Public methods: can be called by anyone. (except for initialize, which is always private)
 ii). Protected methods: can be invoked only by objects of the defining class and its sub-classes.
 iii). Private methods: can be called only in the context of the current object.

 

If a method is protected, it may be called by any instance of the defining class or its subclasses. If a method is private, it may be called only within the context of the calling object—it is never possible to access another object’s private methods directly, even if the object is of the same class as the caller.

 

 

4, Variables

 

in Ruby, a variable is simply a reference to an object. Objects float around in a big pool somewhere (the heap, most of time) and are pointed to by variables.

Using the dup method of String, which creates a new String object with identical contents

for example:

 

  person1 = "Tim"
  person2 = person1.dup

person1 和 person2 创建了两个不同的String Object, 内容是相同的。



You can also prevent anyone from changing a particular object by freezing it.

for example:

 

  person1 = "Tim"
  person2 = person1
  person1.freeze
  person2[0] = "J"

 

There will be a RuntimeError

 

 

Containers, Blocks, and Iterators

Ruby comes with two built-in classes to handle collections: arrays and hashes. Mastery of these two classes is key to being an effective Ruby programmer .

Array

You can treat arrays as stacks, sets, queues, dequeues, and FIFO queues

for example:
  Stacks: use push and pop methods
  FIFO queues: use push and shift methods

 

 

Hash

 

You can index a hash with objects of any type: symbols strings regular expressions and so on.

 

the pattern [\w']+ : which matches sequences containing "word characters" and single quotes

 

 

Block

 

Block can appear in Ruby source code only immediately after the invocation of some method.

 

important rule: if there's a variable inside a block with the same name as a variable in the same scope outside the block, the two are the same.
在block内和外的变量名是重名的, 那么这两个变量是一样的

 

IN RUBY1.9: parameters to a block are now always local to a block, even if they have the same name as locals in the surrounding scope.

还要注意: 是参数和外部变量的名重合, 不会有问题,但是外部变量和内部变量重合, 就会有问题

 

A Block may also return a value to the method.

 

collect which takes each element from the collection and passes it to the block. the results returned by the block are used to construct a new array.   ( each, map 都可以返回数组 )

each_with_index : keep track of how many times you've been through the block.

inject : lets you accumulate a value across the memebers of a collection.

inject(:+)    inject(:*)

 

 

Enumerators -- External Iterators

 

Ruby 的外部迭代 & 内部迭代

一个基本的问题是决定到底由哪一方来控制迭代,是迭代器自身还是使用迭代器的客户代码?当客户代码控制迭代时,该迭代器被称为外部迭代器,反之当迭代器控 制迭代时,该迭代器就是一个内部迭代器。那些使用外部迭代器的客户代码必须负责推进整个遍历过程并且显式的从迭代器中获得下一个元素。相比之下,在使用内 部迭代器时,客户代码将一个操作传递给一个内部迭代器,该迭代器依次在每个元素上应用该操作。

外部迭代器比内部迭代器更灵活。比如,使用外部迭代器可以很容易的比较两个集合的相等性,如果用内部迭代器则不太可能。但是从另一个角度来看,内部迭代器更容易使用,因为它们已经为你定义好了迭代逻辑。

在Ruby中,像each这样的迭代器方法是内部迭代器,它们控制着迭代并且将值“推送”给那个与方法调用相关联的代码块。Enumerator 枚举器具有一个each方法,可用于内部迭代,但是在Ruby1.9及其后的版本里,它们还能充当外部迭代器,客户代码可以使用next方法顺序的从一个 枚举器中“取出"值。

 

loop 比较两个集合

 

 

 

内容概要:本文深入探讨了Kotlin语言在函数式编程和跨平台开发方面的特性和优势,结合详细的代码案例,展示了Kotlin的核心技巧和应用场景。文章首先介绍了高阶函数和Lambda表达式的使用,解释了它们如何简化集合操作和回调函数处理。接着,详细讲解了Kotlin Multiplatform(KMP)的实现方式,包括共享模块的创建和平台特定模块的配置,展示了如何通过共享业务逻辑代码提高开发效率。最后,文章总结了Kotlin在Android开发、跨平台移动开发、后端开发和Web开发中的应用场景,并展望了其未来发展趋势,指出Kotlin将继续在函数式编程和跨平台开发领域不断完善和发展。; 适合人群:对函数式编程和跨平台开发感兴趣的开发者,尤其是有一定编程基础的Kotlin初学者和中级开发者。; 使用场景及目标:①理解Kotlin中高阶函数和Lambda表达式的使用方法及其在实际开发中的应用场景;②掌握Kotlin Multiplatform的实现方式,能够在多个平台上共享业务逻辑代码,提高开发效率;③了解Kotlin在不同开发领域的应用场景,为选择合适的技术栈提供参考。; 其他说明:本文不仅提供了理论知识,还结合了大量代码案例,帮助读者更好地理解和实践Kotlin的函数式编程特性和跨平台开发能力。建议读者在学习过程中动手实践代码案例,以加深理解和掌握。
内容概要:本文深入探讨了利用历史速度命令(HVC)增强仿射编队机动控制性能的方法。论文提出了HVC在仿射编队控制中的潜在价值,通过全面评估HVC对系统的影响,提出了易于测试的稳定性条件,并给出了延迟参数与跟踪误差关系的显式不等式。研究为两轮差动机器人(TWDRs)群提供了系统的协调编队机动控制方案,并通过9台TWDRs的仿真和实验验证了稳定性和综合性能改进。此外,文中还提供了详细的Python代码实现,涵盖仿射编队控制类、HVC增强、稳定性条件检查以及仿真实验。代码不仅实现了论文的核心思想,还扩展了邻居历史信息利用、动态拓扑优化和自适应控制等性能提升策略,更全面地反映了群体智能协作和性能优化思想。 适用人群:具备一定编程基础,对群体智能、机器人编队控制、时滞系统稳定性分析感兴趣的科研人员和工程师。 使用场景及目标:①理解HVC在仿射编队控制中的应用及其对系统性能的提升;②掌握仿射编队控制的具体实现方法,包括控制器设计、稳定性分析和仿真实验;③学习如何通过引入历史信息(如HVC)来优化群体智能系统的性能;④探索中性型时滞系统的稳定性条件及其在实际系统中的应用。 其他说明:此资源不仅提供了理论分析,还包括完整的Python代码实现,帮助读者从理论到实践全面掌握仿射编队控制技术。代码结构清晰,涵盖了从初始化配置、控制律设计到性能评估的各个环节,并提供了丰富的可视化工具,便于理解和分析系统性能。通过阅读和实践,读者可以深入了解HVC增强仿射编队控制的工作原理及其实际应用效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值