How to initialize an array in one step using Ruby?
You can use an array literal:
array = [ '1', '2', '3' ]
You can also use a range:
array = ('1'..'3').to_a # parentheses are required
# or
array = *('1'..'3') # parentheses not required, but included for clarity
For arrays of whitespace-delimited strings, you can use Percent String syntax:
array = %w[ 1 2 3 ]
You can also pass a block to Array.new
to determine what the value for each entry will be:
array = Array.new(3) { |i| (i+1).to_s }
Finally, although it doesn't produce the same array of three strings as the other answers above, note also that you can use enumerators in Ruby 1.8.7+ to create arrays; for example:
array = 1.step(17,3).to_a
#=> [1, 4, 7, 10, 13, 16]
Initialize method with array in Ruby
You have multiple ways of solving your problem :
- First
friends
could be array of names (string)
class User
attr_accessor :name, :friends
def initialize(name, friends)
@name = name
@friends = friends
end
def friendNbr
return friends.count
end
def isFriendWith(value)
friends.each do |friend_name|
if (friend_name == value)
return "Yes, #{name} is friend with #{friend_name}"
end
end
return "No, #{name} is not friend with #{friend_name}"
end
end
jane = User.new("Jane", ["Boris", "Francois", "Carlos", "Alice"])
bob = User.new("Bob", ['Jane', 'Boris', 'Missy'])
alice = User.new("Alice", ['Bob', 'Jane'])
bob.isFriendWith("Jane")
jane.isFriendWith("Alice")
alice.isFriendWith("Carlos")
- Other way is to pass object as you did but in this case you can only pass object already instanciated. In this second choice you can add a method
addFriend
and first createUser
and then add themfriends
.
class User
attr_accessor :name, :friends
def initialize(name, friends)
@name = name
@friends = friends
end
def friendNbr
return friends.count
end
def isFriendWith(value)
friends.each do |user|
if (user.name == value)
return "Yes, #{name} is friend with #{user.name}"
end
end
return "No, #{name} is not friend with #{value}"
end
def addFriend(...)
...
end
end
jane = User.new("Jane", [])
bob = User.new("Bob", [jane])
alice = User.new("Alice", [bob, jane])
bob.isFriendWith("Jane")
jane.isFriendWith("Alice")
alice.isFriendWith("Carlos")
Ruby Array Initialization
Arguments are always evaluated prior to a method call whereas a block is evaluated only during the method call at a timing controlled by the method (if it is ever evaluated).
In your first example, the argument "abc"
is evaluated once before the method new
is called. The evaluated object is passed to the method new
. The exact same object is used in the all three elements of the created array. Modifying one means modifying all of them.
In your second example, the block {"abc"}
is evaluated each time a new element is generated for the array. The three elements in the created array are different objects.
How to Initialize Class Arrays in Ruby
You need to use initialize as a constructor as below code and is there any reason why not to use initialize/constructor. And please fix a typo error in class definition Class Something
to class Something
no camel case or first letter capitalize while in class
class Something
def initialize
@something = Array.new
end
def dosomething
s = 5
@something << s
end
end
class variable @@
are available to the whole class scope. so they are working in the code and if you want to use instance variable @ you need to initialize it as above. The instance variable is share with instance/objects of a class
for more details visit the link Ruby initialize method
Initialize an Array with optional elements depending on conditions
I'm not sure if this is a good way of doing it, but here's my suggestion:
array = [
"1st element",
flag? ? "2nd element" : nil,
"3rd element"
].compact
.compact
will remove all the nil
values from your array. This will be problematic if you might have nil values.
Ruby array initialize on read
Something like:
a[12] = (a[12] ||= 0) + 1
How to initialise multiple array in single line in Ruby?
if I return it like
[[],[]]
it is working fine but in the later case, 3 arrays will get initialize which I want to avoid?
It cannot be avoided because a method can only return a single object.
So wrapping the objects in [...]
is just fine:
def fetch_group_dept_values
if condition
[[1, 2, 3,], [4, 5]]
else
[[9, 15], [10, 11]]
end
end
The overhead of creating a (small) extra array is negligible.
However, you could avoid the outer array by yielding the values instead of returning them:
def fetch_group_dept_values
if condition
yield [1, 2, 3,], [4, 5]
else
yield [9, 15], [10, 11]
end
end
And call it via:
fetch_group_dept_values do |groups, departments|
# ...
end
Ruby: how to initialize an array across several lines
You will want to put the comma, after the item like so
myarray = [
"string 1",
"string 2",
"string 3"
]
Also, if you might be thinking of putting the comma before the item, for say easy commenting or something like that while your working out your code. You can leave a hanging comma in there with no real adverse side effects.
myarray_comma_ended = [
"test",
"test1",
"test2", # other langs you might have to comment out this comma as well
#"comment this one"
]
myarray_no_comma_end = [
"test",
"test1",
"test2"
]
Related Topics
Connecting Rails 3.1 With Multiple Databases
Best Way to Create Custom Config Options For My Rails App
Save Image from Url by Paperclip
Best Way to Escape and Unescape Strings in Ruby
Naked Asterisk as Parameter in Method Definition: Def F(*)
Paginating an Array in Ruby With Will_Paginate
Rails: Activerecord Query Based on Association Value
How to Override a Setter Method in Ruby on Rails
How to Keep the Delimiters When Splitting a Ruby String
How to Find and Return a Duplicate Value in Array
Eventsource/Server-Sent Events Through Nginx
The 'Json' Native Gem Requires Installed Build Tools
Pass Parameter by Reference' in Ruby
Is There a Clean Way to Avoid Calling a Method on Nil in a Nested Params Hash
Why Are Gems Installed in a Directory With a Different Ruby Version Than I'M Running
Ruby 2.4 and Rails 4 Stack Level Too Deep (Systemstackerror)
Ruby 1.9: How to Properly Upcase & Downcase Multibyte Strings