Control Structure Flashcards
What are the conditional statements available in Ruby?
1) if
2) Case
3) unless
How we can use if condition?
If conditon can be used in threee variants
if
end
if
else
end
if
elsif
else
end
What is very popular one line condtitional statement?
tenary operator
condition ? true : false
Can case statements be assigned to any variable?
yes. This value can be assigned to a variable preceding the case statement.
happy = case
when …
end
What is the alternative way of expressing ‘if not’.?
unless
What the looping structures available in Ruby?
for,until,while,loop
Is each a loop?
no, its an iterator.Also it can be used as built in methods in classes like array,hash
How we can use for loop?
It can be used in three different ways.
for i in 1..10
end
for i in 1..10 do
end
single line
for i in 1..10 do end - do is mandatory
give the while loop alternate syntax?
i = 0 begin puts(arr[i]) i += 1 end while i < arr.length
give the until loop alternate syntax?
i = 0 until i == arr.length puts(arr[i]) i +=1 end
How “loop” keywords can be used in Ruby?
loop do
end
loop {
}
What is a statement modifier?
A condition which follows a statement such as with x = 1 if a == true
Does the case statement in Ruby have fall-through behavior?
No. Fall through means , control moves to the matching case, and then execution continues (“falls through”) to the statements associated with the next case. fallthrough is usually prevented with a break keyword at the end of the matching body
What are some advantages of a case statement versus repeated elsif statements?
It shows intent. It DRY’s out the condition.
Why might you use #each instead of for/in?
It’s the “Ruby way” - an example of how Ruby defines methods that mimic natural language concepts. Iterator methods such as #each read more naturally. #each is a block so it defines a new variable scope. for/in depends on the existence of #each which implies that #each is a more fundamental aspect of the language.