如何检查ruby变量中只有一个对象?

时间:2017-09-14 07:58:34

标签: ruby-on-rails

我有一个ruby变量@object,里面只能有一个对象或多个对象 如何在Rails中检查。 尝试用

检查
.length
.size
.count 

2 个答案:

答案 0 :(得分:1)

迈克尔的答案应该已经有效了,但另一个选择是检查它是否包含@object.is_a? Enumerable # => returns true if Array-ish or false 模块(应该支持所有“数组”-ish对象,除非他们有自己的自定义实现):

# Array
[].is_a? Enumerable
# => true

# Hash
{}.is_a? Enumerable
# => true

# Set
[].to_set.is_a? Enumerable
# => true

# Subclass of any of the above
class MyArr < Array
end
MyArr.new.is_a? Enumerable
# => true

# ActiveRecord::Relation
User.all.is_a? Enumerable
# => true

# String
'somestring'.is_a? Enumerable
# => false

# Integer/Float
123.is_a? Enumerable
# => false
(123.45).is_a? Enumerable
# => false

# Time
Time.now.is_a? Enumerable
# => false

实施例

## Rails 4:
ActionController::Parameters.new.is_a? Enumerable
# => true

## Rails 5:
ActionController::Parameters.new.is_a? Enumerable
# => false
# in Rails 5, ActionController::Parameters no longer inherits from Hash

# ActionController::Parameters is the type of the variable `params` in your controllers
# Because practically speaking you can loop over it, so it should still be an "Array"
# Therefore, you might want to use the following instead of `.is_a? Enumerable`
@object.respond_to? :each
# => returns true if Array-ish or false

ActionController::Parameters.new.respond_to? :each
# => true

疑难杂症

 Package                      Version   Latest      Type
---------------------------- --------- ----------- -----
bleach                       1.5.0     2.0.0       wheel
html5lib                     0.9999999 0.999999999 wheel
jupyter-contrib-nbextensions 0.3.0     0.3.1       wheel
...
murmurhash                   0.26.4    0.28.0      sdist
nbconvert                    5.2.1     5.3.1       wheel
pyasn1-modules               0.1.1     0.1.4       wheel


⇒  sudo pip3 install html5lib

Password:
The directory '/Users/william/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/Users/william/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Requirement already satisfied: html5lib in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages
Requirement already satisfied: six in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from html5lib)**

答案 1 :(得分:0)

您可以使用respond_to?方法

@object.respond_to? :size

如果对象数组

,则返回true